开发者

Convert VB.NET "Shared Widening Operator" to c#

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

Public Shared Widen开发者_StackOverflow社区ing 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, i.e. 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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜