简体   繁体   English

何时在 C# 中使用隐式和显式运算符

[英]When to use implicit and explicit operators in C#

Writing implicit and explicit type conversion operators is trivial.编写隐式和显式类型转换运算符很简单。

I can find lots of documentation about how to write them, but very little about when , or why to write them.我可以找到很多关于如何编写它们的文档,但关于何时为什么编写它们的文档却很少。

I've done some investigations into existing implementations;我对现有的实现做了一些调查; for example, BigInteger from .NET's reference source:例如,来自 .NET 参考源的BigInteger

public struct BigInteger : IFormattable, IComparable, IComparable<BigInteger>, IEquatable<BigInteger>
{
    public static implicit operator BigInteger(Byte value)
    {
        return new BigInteger(value);
    }

    public static explicit operator Byte(BigInteger value)
    {
        return checked((byte)((int)value));
    }
}

Given the excerpt above, what is the rational for using an implicit operator when converting from Byte to BigInteger , but using an explicit operator when converting from BigInteger to Byte ?鉴于上面的摘录,从Byte转换为BigInteger时使用implicit运算符但从BigInteger转换为Byte时使用explicit运算符的合理性是什么?

As I mentioned in my comment, my assumption was that implicit operators should always be considered safe, whereas explicit operators may be safe but in some cases may need to be handled.正如我在评论中提到的,我的假设是隐式运算符应该始终被认为是安全的,而显式运算符可能是安全的,但在某些情况下可能需要处理。

I found the following documentation on pre-defined implicit operators:我在预定义的隐式运算符上找到了以下文档

The pre-defined implicit conversions always succeed and never cause exceptions to be thrown.预定义的隐式转换总是成功并且不会引发异常。

Note: Properly designed user-defined implicit conversions should exhibit these characteristics as well.注意:正确设计的用户定义的隐式转换也应该表现出这些特征。 end note尾注

In addition, the documentation for explicit conversions does not give the same guarantees:此外,显式转换的文档没有提供相同的保证:

The explicit conversions that are not implicit conversions are conversions that cannot be proven always to succeed, conversions that are known possibly to lose information, and conversions across domains of types sufficiently different to merit explicit notation.非隐式转换的显式转换是不能被证明总是成功的转换、已知可能丢失信息的转换以及跨类型域的转换足够不同以值得显式表示法。

This clearly backs up my assumption that implicit operators must ALWAYS be safe and never require exception handling, whereas explicit operators can and do throw exceptions, as in your example of the explicit operator that is checked .这清楚地支持了我的假设,即隐式运算符必须始终是安全的并且永远不需要异常处理,而显式运算符可以并且确实会抛出异常,如您的显式运算符示例中所checked的那样。

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

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