我正在尝试使用自定义整数类型,遇到了一个涉及泛型,隐式转换和32位整数的有趣问题。
下面是如何重现该问题的精简示例。如果我有两个隐式方法要转换int为MyInt,反之亦然,那么我会收到一个编译错误,看起来像C#无法解析要使用的泛型类型。并且仅在int或时发生uint。所有其它整数类型做工精细:sbyte,byte,short,ushort,long,ulong。
如果删除隐式转换方法之一,它也可以正常工作。与循环隐式转换有关?
using Xunit;
public class MyInt
{
public int Value;
//If I remove either one of the implicit methods below, it all works fine.
public static implicit operator int(MyInt myInt)
{
return myInt.Value;
}
public static implicit operator MyInt(int i)
{
return new MyInt() { Value = i };
}
public override bool …Run Code Online (Sandbox Code Playgroud)