最有可能的工作代碼:
public static class TestClass
{
public const int constValue1 = 1;
public const int constValue2 = 2;
public const int constValue3 = 3;
}
enum TestEnum
{
testVal1, testVal2, testVal3
}
public int TestFunction(TestEnum testEnum)
{
switch (testEnum)
{
case TestEnum.testVal1:
return TestClass.constValue1;
case TestEnum.testVal2:
return TestClass.constValue2;
case TestEnum.testVal3:
return TestClass.constValue3;
}
return 0; // all code paths have to return a value
}
首先,根據const (C# Reference):
的常量關鍵字被用於修改一個字段或局部變量的聲明。它指定字段或局部變量的值是常量,這意味着它不能被修改。
在C#,const
僅作爲一個字段(如TestClass.constValue1
)或局部變量,不適合於函數返回類型的改性劑。
所以你是來自偉大的C/C++王國。我非常有限的知識,C/C++的思考,在C/C const
返回類型++只與指針有意義...
// C++ code
const int m = 1;
// It returns a pointer to a read-only memory
const int* a(){
return &m;
}
但是,除非你正在使用不安全的代碼,存在沒有指針C#。只有值類型(如int
/DateTime
/TestEnum
/結構)和引用類型(如string
/類)。在網上閱讀的內容還有很多。
所以如同int
是C#中的一個值類型,當你返回它時,它會得到複製。因此,即使您要返回「常量int
」,返回的值爲也不是常量,並且修改返回值將而不是「更改常數並導致SegFault」。
嗯,我忘了回答你的問題......
究竟如何,函數的返回類型會是什麼? (我正在使用對象返回類型,這不會引發任何錯誤)
就像我在上面的代碼中顯示的那樣,int
。
const int blah = 1
只聲明int
類型的變量/字段blah
哪一個不能修改它(通過執行blah = 2
)。在C#const int
中是而不是的一種類型。
有沒有其他選項可以實現?
嗯......我想我實際上並不需要回答這個...
你是從C/C++的世界裏,對不對?在C#中沒有像const char []這樣的東西。 –
他他確切Alvin –
此外,你的代碼根本不會是正確的,因爲'case'應該在'switch'塊內。你的「Enum」似乎也不正確。 –