您如何 return 在 C# 中隐式缩小和扩大的 UInt?

How do you return an UInt that implicitly narrows and widens in C#?

在 C# 中,您有一些运算符会根据结果的大小隐式缩小和扩大结果变量。

 UInt32 exampleA = 10000000/2;      // Will return a UInt32 
 UInt32 exampleB = 1000000000000/2; // Will implicitly widen to UInt64 and cause a compile error
 UInt64 exampleC = 1000000000000/2; // Will implicitly widen to UInt64 without error

你能为一个方法做这个吗?如果可以,怎么做?我相信它与通用协方差和反方差有关,但我不确定如何为下面的函数实现它

// Will compile but won't automatically widen
UInt32 validVariable= exampleFunction(1,1);
UInt32 invalidVariable = exampleFunction(UInt32.MaxValue,1);

private static UInt32 exampleFunction(UInt32 x, UInt32 y)
{
     return (x+y); //
}

// Won't compile but will automatically widen
UInt32 validVariable= exampleFunction(1,1); // Will cause compile error
UInt32 invalidVariable = exampleFunction(UInt32.MaxValue,1); // Will cause compile error

private static UInt64 exampleFunction(UInt32 x, UInt32 y)
{
     return (x+y); //
}

这与泛型或变体无关。并不是算子自己加宽或变窄。允许编译器为输入和输出插入隐式转换。你的两个编译器错误都是由于没有从 ulonguint 的内置转换引起的。如果需要,编译器将插入从 uintulong 的隐式转换。除法运算符的观察行为是因为有两个重载可供编译器选择。您要做的等效事情是使用签名定义两个重载:

uint exampleFunction(uint x, uint y)
ulong exampleFunction(ulong x, ulong y)

然后如果其中一个参数恰好是更宽的 ulong 类型,编译器将选择第二个重载,因为允许插入从 uintulong 的转换。