[英]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.