繁体   English   中英

如何将变量的不同值分配给同一对象的不同实例?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM