在C#中,要編寫簡潔的靜態變量代碼,您可以使用靜態類
public static class Constants
{
public const string MyStaticVariable = "SomeValue";
public const int MyStaticInteger = 42;
public static readonly double MyStaticDouble = 3.14;
}
在這個示例中,我們創建了一個名為Constants
的靜態類,并在其中定義了三個靜態變量:一個字符串(MyStaticVariable
),一個整數(MyStaticInteger
)和一個雙精度浮點數(MyStaticDouble
)。注意,對于只讀變量,我們使用了readonly
關鍵字。
要在其他類中使用這些靜態變量,只需添加對包含靜態類的命名空間的引用,然后使用類名作為變量前綴:
public class MyClass
{
public void PrintConstants()
{
Console.WriteLine($"String constant: {Constants.MyStaticVariable}");
Console.WriteLine($"Integer constant: {Constants.MyStaticInteger}");
Console.WriteLine($"Double constant: {Constants.MyStaticDouble}");
}
}
這種方法使您的代碼更加整潔,易于維護和重用。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。