C# 中隐式变量赋值的示例
我注意到您可以在 C# 中执行此类操作:
XNamespace c = "http://s.opencalais.com/1/pred/";
注意字符串值已隐式转换为不同的类型。还有其他地方可以做到这一点吗?围绕此类事情有哪些常见的模式和做法?
I noticed you can do this sort of thing in C#:
XNamespace c = "http://s.opencalais.com/1/pred/";
Notice the string value is implicitly converted to different type. Are there other places this can be done? What are some common patterns and practices around this sort of thing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
每当使用隐式转换运算符时,就会发生这种情况定义的。总而言之,这是相当罕见的。
This can happen whenever an implicit conversion operator is defined. All in all it is quite rare.
这应该有帮助
http://msdn.microsoft.com/en-us/library/z5z9kes2。 aspx
编辑:Matt ninja'd :)
this should help
http://msdn.microsoft.com/en-us/library/z5z9kes2.aspx
edit: Matt ninja'd it :)
令人惊讶的是,我第一次看到这个是在关于 C# 转换运算符的 Wikipedia 文章上,我以前从未见过有人使用过这个。似乎这会损害可读性并使很多开发人员感到困惑......
Surprisingly, the first time I saw this was on the Wikipedia article about C# Conversion operators, I've never actually seen anyone use this before. Seems like it would hurt readability and confuse a lot of developers...
基本上,XNamespace 提供了一个执行隐式转换的运算符。
我想大多数常识性指南都适用,只在有意义的地方使用它并避免混淆。最大的问题是意外的隐式转换,这可能会导致编程错误。您可以避免这种情况,并且仍然使用显式转换运算符提供转换。
您希望使用显式转换运算符而不是隐式转换运算符的一个示例是允许从浮点类型进行转换的整数类;隐式转换会隐藏必须发生的截断/舍入,从而使用户非常困惑(并且可能是错误的根源)。
在我的代码中,我已经使用过它几次,例如在非常简单的验证结果结构,它提供了到 bool 的隐式转换(但不是从 bool 到 bool 的隐式转换)。这让我可以执行
if (result) { ... }
(不过,对于它的用处,目前还没有定论:))。我猜它的大部分用途是用于“简单”数据类型,如大整数、小数等。
Basically XNamespace provide an operator that performs implicit conversion.
I guess most common-sense guidelines apply, only use it where it makes sense and avoid confusion. The biggest problem is unintended implicit conversion which could potentially open up for programming errors. You can avoid this and still provide a conversion with an explicit conversion operator.
An example of a case where you would want to use an explicit conversion operator instead of an implicit one would be a integer class that allows conversion from a floating point type; an implicit conversion would hide the truncation/rounding that would have to take place and could thus make the user very confused (and probably be the source of bugs.)
In my code I've used it a couple of times, for example in a very simple validation result struct which provided implicit conversion to bool (but not from). This allowed me to do
if (result) { ... }
(the jury is still out about the usefulness of this though :)).Guess most of its use is for "simple" datatypes, like big integers, decimals and likewise.