简体   繁体   中英

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

这些运算符的用途是什么?

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.

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

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