When must we use implicit and explicit operators in C#?

蓝咒 提交于 2019-11-30 05:12:15

问题


What is the usage of these operators?


回答1:


Basically when you want to provide conversions between types. LINQ to XML provides good examples... There's an implicit conversion from string to XName, so you can write:

XName name = "element";

but there's an explicit conversion from XAttribute to int (and many other types) so you have to include a cast in your code:

int value = (int) element.Attribute("age");

Think very carefully before providing implicit conversions - they're rarely a good idea; LINQ to XML uses them to great effect, but they can be confusing. Even explicit user-defined conversions can surprise the unwary reader.




回答2:


They are used when doing operator overloading. Here's a link to a MSDN article.



来源:https://stackoverflow.com/questions/2371011/when-must-we-use-implicit-and-explicit-operators-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!