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