C#获取、设置属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14922286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 13:27:41  来源:igfitidea点击:

C# get, set properties

c#propertiesgetset

提问by coder

I have the following code:

我有以下代码:

    private void button1_Click(object sender, EventArgs e)
    {
        Class1 myClass = new Class1("ttt");
        myClass.Name = "xxx";
        MessageBox.Show(myClass.Name);
    }

and

class Class1
{
    string str = "";

    public Class1(string name)   
    {
        str = name;
    }

    public string Name
    {
        get { return str; }
        set;

    }
}

Initially I set:

最初我设置:

  myClass.Name = "ccc";

but later changed it to:

但后来改为:

  myClass.Name = "xxx";

and also changed:

并且还改变了:

  set {str = value;}

to:

到:

  set;

Why when I run it do I get "ccc" instead of "xxx" ?

为什么当我运行它时,我得到的是“ccc”而不是“xxx”?

In my current code there is "ccc".

在我当前的代码中有“ccc”。

回答by bas

Change your Nameproperty as follows:

更改您的Name属性如下:

public string Name
{
    get { return str; }
    set { str = value; }
}

To answeryour question, the reason why you get "ccc" instead of "xxx" is that you have compile errors. When you run your application it will ask you if you want to run the latest known working configuration. The last time your program did compile, you used "ccc" as literal, and that is what is still running.

为了回答你的问题,你得到“ccc”而不是“xxx”的原因是你有编译错误。当您运行应用程序时,它会询问您是否要运行最新的已知工作配置。上次您的程序编译时,您使用了“ccc”作为字面量,这就是仍在运行的内容。

Fix the compile errors and run it again, and then it will be "xxx"

修复编译错误,再次运行,就会是“xxx”

回答by Immortal Blue

public string Name
{
    get { return str; }
    set;

}

should be

应该

public string Name
{
    get { return str; }
    set { str = value; }
}

回答by pjm

The pattern

图案

public string Name {get;set;}

is what is called "Auto-Implemented Properties".

就是所谓的“自动实现的属性”。

The compilier creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

编译器创建一个私有的、匿名的支持字段,只能通过属性的 get 和 set 访问器访问。

What you original code seems to be doing is get on a field you defined but a set on the anonymous backing field. Therefore build error ...

您的原始代码似乎正在做的是获取您定义的字段,但获取匿名支持字段的集合。因此构建错误...