简体   繁体   English

什么时候必须在C#中使用隐式和显式运算符?

[英]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: LINQ to XML提供了很好的示例...从字符串到XName都有隐式转换,因此您可以编写:

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: 但是从XAttributeint (以及许多其他类型)有显式转换,因此您必须在代码中包括XAttribute类型转换:

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. LINQ to XML使用它们产生了很大的效果,但是它们可能会造成混淆。 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 . 这是MSDN文章的链接。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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