简体   繁体   中英

Convert VB.NET “Shared Widening Operator” to c#

I have converting this method from vb.net to c#:

Public Shared Widening Operator CType(ByVal items As MyOption()) As MyOptionCollection
   Return New MyOptionCollection(items)
End Operator

My complaint is that I do not know what this function can complete. I also want to think of how it is working. I find that "Widening Operator" means that when you cast the cast will work but I don't think I have the full meaning.

How can I convert this to c#? Too can you please send me to where I learn what this does ?

This is a conversion operator that takes array of MyOption references and returns an reference to MyOptionCollection object. "Widening" means that using this conversion, you won't lose any data. "Operator" means that it can be called with special syntax.

In C#, Widening can be replaced with implicit (altough I believe it is not exactly the same). So it'll be:

public static implicit operator MyOptionCollection(MyOption[] items)
{
   return new MyOptionCollection(items);
}

You can read about conversion operators in C# at MSDN .

More about widening/narrowing: When the operator is narrowing, it means that you can possibly lose (some of) your data. Good example is casting from Int64 to Int32 . If the value is less than maximal for Int32 , the cast will succeed and the value will be persisted. But otherwise it will fail. Contrary, widening operator can't lose any data, ie casting from Int32 to Int64 - you can always do it safely.

A Widening operator is one that can perform a conversion without losing precision/information. As such, it is one that would be safe to declare in C# as an implicit operator.

So the equivalent in C# would be something like:

public static implicit operator MyOptionCollection(MyOption[] items)
{
   return New MyOptionCollection(items);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM