1
在C#中,操作符会根据结果的大小隐式缩小和扩大结果变量。如何返回一个在C#中隐式缩小和扩大的UInt?
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); //
}
不完全确定你的意思是扩大。常数被定义为“1000000000000”,这是一个“长”。你将它的分割结果存入'UInt64'中(通常是?)'ulong'。两者都是64位。在'long a = 1'的情况下,会发出编译器指令:'conv.i8',它将值(int)转换为64位值。另请注意,该分解由编译器解决,它只是简单地发射常量。 – Rob
你所有的例子都非常多,如你所描述的那样编译或不编译。你到底在问什么?你想创建自己的类型,如“UInt32”? – Kobi
@Kobi我想知道如何创建一个函数,该函数根据函数中的返回值自动返回最小的UInt类型。 正如答案中所示,我对运营商如何展示这种行为做了一个错误的假设,这种行为是基于我的逻辑,我真正需要的是重载行为的重载 – Puddler