[英]How to assign different values of variables to different instances of the same object?
我正在嘗試建立一個非常基本的系統,該系統通過其構造函數創建一個Levels對象:
class Levels
{
// private level properties
private static string levelName { get; set; }
private static int levelSize { get; set; }
private static int levelNum { get; set; }
// new level constructor. Takes name, size (to square) and level number.
public Levels(string inName, int inSize, int inNum)
{
levelName = inName;
levelSize = inSize;
levelNum = inNum;
}
// ... GetLevel methods here...
}
並將這些值分配給對象的每個特定實例。 但是輸出告訴我,levelName,levelSize和levelNum變量未正確“粘貼”到每個實例。
class Program
{
static void Main(string[] args)
{
var Level1 = new Levels("Forest", 15, 1);
var Level2 = new Levels("Desert", 22, 2);
Console.WriteLine($"--- {Level1.GetLevelName()}, level {Level1.GetLevelNum()} ---");
Console.WriteLine($"--- {Level2.GetLevelName()}, level {Level2.GetLevelNum()} ---");
Console.ReadLine();
}
}
// output:
// --- Desert, level 2 ---
// --- Desert, level 2 ---
// why is level 1 not displaying here?
我知道,如果我要在第一個WriteLine命令之后將級別2的構造函數移走,那實際上是可行的,但是顯然我需要這些值堅持其實例。
關鍵字static
表示變量不是實例級別,而是類級別。 這意味着您的變量將在Levels
類的所有實例之間共享。
我建議將其重寫為:
public class Levels
{
public string LevelName { get; private set; }
public int LevelSize { get; private set; }
public int LevelNum { get; private set; }
// new level constructor. Takes name, size (to square) and level number.
public Levels(string inName, int inSize, int inNum)
{
LevelName = inName;
LevelSize = inSize;
LevelNum = inNum;
}
}
現在,您將使用具有私有設置器的Properties (這意味着它們只能在類內部設置),而不是使用變量為private static
。 現在,您的每個Levels
實例都有各自的值,實例之間沒有任何共享。 這也將給您帶來額外的好處,那就是消除了對GetLevelName()
, GetLevelNum()
等方法的需要。 您現在可以說:
Console.WriteLine($"--- {Level1.LevelName}, level {Level1.LevelNum} ---");
我在這里擺弄小提琴進行演示。
從字段中刪除static
關鍵字。 基本上, static
關鍵字表示該字段對於此類的所有實例都是相同的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.