为何C#中==运算符仅支持WrappedInt转int的隐式转换,反之则不行?
为什么C#中使用==运算符时,仅类→int的隐式转换有效,int→类却无效?
问题详情
在C#里,使用带隐式类型转换的==运算符时,只有在自定义类中定义类到int的隐式转换时,int和自定义类的比较能正常工作;但如果只定义int到类的隐式转换,比较就会报错。
示例代码如下:
using System; public class WrappedInt { private int Value { get; } public WrappedInt(int value) { Value = value; } // 定义这个转换时,Main中的比较正常运行 public static implicit operator int(WrappedInt wInt) => wInt.Value; // 换成这个转换的话,比较会报错:运算符 '==' 无法应用于 'int' 和 'WrappedInt' 类型的操作数 // public static implicit operator WrappedInt(int value) => new WrappedInt(value); } public class Program { public static void Main() { var a = 2; var b = new WrappedInt(2); var areSame = a == b; Console.WriteLine(areSame); } }
即使把a == b改成b == a也无法解决错误,说明这不是操作数顺序的问题,推测和int是基元类型有关。
后续思考1
有意思的是,下面这段比较两个不同包装类WrappedInt1和WrappedInt2的代码能正常运行,尽管它们都只定义了到int的隐式转换。看起来==运算符会把这两个包装对象都转换成int后再比较。
代码示例:
using System; public class WrappedInt1 { private int Value { get; } public WrappedInt1(int value) { Value = value; } public static implicit operator int(WrappedInt1 wInt) => wInt.Value; } public class WrappedInt2 { private int Value { get; } public WrappedInt2(int value) { Value = value; } public static implicit operator int(WrappedInt2 wInt) => wInt.Value; } public class Program { public static void Main() { var a = new WrappedInt1(2); var b = new WrappedInt2(2); var areSame = a == b; Console.WriteLine(areSame); } }
后续思考2
在==运算符的处理上,int确实有特殊性。下面这段代码尝试比较仅支持互相隐式转换的两个包装类,结果无法编译通过。
代码示例:
using System; public class WrappedInt1 { public int Value { get; } public WrappedInt1(int value) { Value = value; } public static implicit operator WrappedInt2(WrappedInt1 wInt) => new WrappedInt2(wInt.Value); public static implicit operator WrappedInt1(WrappedInt2 wInt) => new WrappedInt1(wInt.Value); } public class WrappedInt2 { public int Value { get; } public WrappedInt2(int value) { Value = value; } public static implicit operator WrappedInt2(WrappedInt1 wInt) => new WrappedInt2(wInt.Value); public static implicit operator WrappedInt1(WrappedInt2 wInt) => new WrappedInt1(wInt.Value); } public class Program { public static void Main() { var a = new WrappedInt1(2); var b = new WrappedInt2(2); var areSame = a == b; Console.WriteLine(areSame); } }
内容的提问来源于stack exchange,提问作者m_ocean
相关产品推荐
相关产品推荐

