简体   繁体   English

在其他公共类中初始化变量时发生C#错误

[英]C# Error when initialize a variable in a different public class

I am trying to initialize 2 different variables in a public class but when I initialize the second one, it gets the property (Name in this example) of the first one. 我正在尝试在公共类中初始化2个不同的变量,但是当我初始化第二个变量时,它将获得第一个变量的属性(在此示例中为Name)。 After I set the name of the second one. 之后,我设置第二个的名称。 The first variable changes its name property to the second name. 第一个变量将其name属性更改为第二个名称。 For example, when I execute the code: 例如,当我执行代码时:

    //Initialization and set of first var
    findLineToolA.Name = "findLineToolA";
    findLineToolB = null;
    //After findLineToolB = new CatFindLineTool();
    findLineToolA.Name = "findLineToolA";
    findLineToolB.Name = "findLineToolA";

    //After findLineToolB.Name = "findLineToolB";
    findLineToolA.Name = "findLineToolB";
    findLineToolB.Name = "findLineToolB";

    public class CatFindLineTool 
    {
            private static string _name;

            public string Name
            {
                set
                {
                    _name = value;
                }
                get
                {
                    return _name;
                }
            }
    }
public class CatFindCornerTool 
{
    public CatFindLineTool findLineToolA;
    public CatFindLineTool findLineToolB;
    public CatFindCornerTool()
    {
     findLineToolA = new CatFindLineTool();
     findLineToolA.Name = "findLineToolA";
     findLineToolB = new CatFindLineTool();
     findLineToolB.Name = "findLineToolB";
    }
   }

I hope someone can help me to figure out why the properties mix up when initialize multiple variables. 我希望有人可以帮助我弄清楚为什么在初始化多个变量时属性会混合在一起。 I guess it is because there is an important concept about C# class that I am ignoring. 我想这是因为我忽略了一个有关C#类的重要概念。 Thanks in advance. 提前致谢。

You have declared the _name field to be static . 您已声明_name字段为static This makes it a 'global' or 'shared' entity across all instances of the class - hence changes to one instance will affect all instances. 这使它成为该类所有实例的“全局”或“共享”实体-因此对一个实例的更改将影响所有实例。

Just remove the static keyword and your code should work as intended. 只需删除static关键字,您的代码即可按预期工作。

Better use Auto-property. 更好地使用自动属性。 You don't have to create a private member for name. 您不必为名称创建私有成员。

A public property 公共财产

public string Name {get;set;}

will automatically create the required private property for you internally. 会在内部自动为您创建所需的私有财产。

Your issue is already addressed by Jens Meinecke 您的问题已由Jens Meinecke解决

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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