我们什么时候必须使用隐性和显性运营商在C#? [英] When must we use implicit and explicit operators in C#?

查看:172
本文介绍了我们什么时候必须使用隐性和显性运营商在C#?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是这些操作符的使用情况如何?

What is the usage of these operators?

推荐答案

基本上当你想类型之间的转换提供。 LINQ到XML提供了很好的例子......这里有一个的的从字符串转换到XName的,所以你可以写:

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";



但有一个的明确的距离转换 XAttribute INT (和许多其他类型的),所以你必须在代码中加入一投:

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");



提供的隐式转换之前非常仔细地考虑 - 他们的很少的一个好理念; LINQ到XML使用它们有很大的影响,但可能会造成混淆。即使是明确的用户定义的转换可以带来惊喜粗心的读者。

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.

这篇关于我们什么时候必须使用隐性和显性运营商在C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆