[英]When to use implicit and explicit operators in C#
编写隐式和显式类型转换运算符很简单。
我可以找到很多关于如何编写它们的文档,但关于何时或为什么编写它们的文档却很少。
我对现有的实现做了一些调查; 例如,来自 .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));
}
}
鉴于上面的摘录,从Byte
转换为BigInteger
时使用implicit
运算符但从BigInteger
转换为Byte
时使用explicit
运算符的合理性是什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.