C# 如何访问自动实现的属性的支持变量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/61480/
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-03 10:20:06  来源:igfitidea点击:

How can I access the backing variable of an auto-implemented property?

提问by public static

In the past we declared properties like this:

过去我们声明属性是这样的:

public class MyClass
{
    private int _age;

    public int Age
    {
          get{ return _age;  }
          set{ _age = value; }
    }
}

Now we can do:

现在我们可以这样做:

public class MyClass
{
    public int Age {get; set;} 
}

My question is, how can I access the private variable that is created automatically using this notation?

我的问题是,如何访问使用此表示法自动创建的私有变量?

I would rather access the private variable and not the public accessor 'Age'. Is there a default notation to access the private variable, or it is just not possible?

我宁愿访问私有变量而不是公共访问器“年龄”。是否有访问私有变量的默认符号,或者根本不可能?

回答by Quibblesome

You can't, it's a language feature as opposed to a IDE feature. To be honest i'd prefer then IDE to add the private variable in for you. I agree that it is slightly weird for the class to internally have to use the public entry point to access its own variables. Hence I don't use this new feature that much myself.

你不能,它是一种语言功能,而不是 IDE 功能。老实说,我更喜欢 IDE 为您添加私有变量。我同意这个类在内部必须使用公共入口点来访问它自己的变量有点奇怪。因此我自己并没有那么频繁地使用这个新功能。

回答by macbirdie

Behind the scenes what happens is the injection of a private member variable, prefixed with <>k__AutomaticallyGeneratedPropertyField#

在幕后发生的是注入一个私有成员变量,前缀为 <>k__AutomaticallyGeneratedPropertyField#

From C# 3.0 Automatic Properties explained

C# 3.0 自动属性解释

Although it may be possible to use that private member directly, it's very hacky and unnecessary.

尽管可以直接使用该私有成员,但它非常笨拙且没有必要。

回答by Scott Dorman

This syntax is commonly called "syntax sugar", which means that the compiler takes that syntax and translates it into something else. In your example, the compiler would generate code that looks something like this:

这种语法通常称为“语法糖”,这意味着编译器采用该语法并将其转换为其他内容。在您的示例中,编译器将生成如下所示的代码:

[CompilerGenerated]
private int <Age>k_BackingField;

public int Age
{
   [CompilerGenerated]
   get
   {
      return this.<Age>k_BackingField;
   }
   [CompilerGenerated]
   set
   {
      this.<Age>k_BackingField = value;
   }

Even knowing all of that, you could probablyaccess the backing field directly but that sort of defeats the purpose of using automatic properties. I say probably here because you then depend on an implementation detail that could change at any point in a future release of the C# compiler.

即使知道了这一切,你可以很可能直接访问支持字段,但那种失败使用自动属性的目的。我在这里说可能是因为您随后依赖于可能在 C# 编译器未来版本中随时更改的实现细节。

回答by chakrit

Your usage of automatic properties implies that you do not need any getting/setting logic for the property thus a private backing variable is unneccessary.

您对自动属性的使用意味着您不需要该属性的任何获取/设置逻辑,因此不需要私有后备变量。

Don't use automatic properties if you have any complex logic in your class. Just go private int _ageand normal getters/setters as you normally would.

如果您的类中有任何复杂的逻辑,请不要使用自动属性。private int _age像往常一样去使用普通的 getter/setter。

IMO, automatic properties are more suited for quickly implementing throwaway objects or temporary data capsules like:

IMO,自动属性更适合快速实现一次性对象或临时数据胶囊,例如:

public class TempMessage {
    public int FromID { get; set; }
    public int ToID { get; set; }
    public string Message { get; set; }
}

Where you don't need much logic.

你不需要太多逻辑的地方。

回答by Wilka

The aim of the new automatic properties is to reduce the amount of boilerplate code you need to write when you just have a simple property that doesn't need any special logic in the get or the set.

新的自动属性的目的是减少当您只有一个不需要 get 或 set 中任何特殊逻辑的简单属性时需要编写的样板代码量。

If you want to access the private member that these properties use, that's usually for a few reasons:

如果您想访问这些属性使用的私有成员,通常有以下几个原因:

  • You need to more than just a simple get/set - in this case, you should just avoid using automatic properties for this member.
  • You want to avoid the performance hit of going through the get or set and just use the member directly - in this case, I'd be surprised if there really was a performance hit. The simple get/set members are very very easy to inline, and in my (admittedly limited) testing I haven't found a difference between using the automatic properties and accessing the member directly.
  • You only want to have public read access (i.e. just a 'get') and the class write to the member directly - in this case, you can use a private set in your automatic property. i.e.

    public class MyClass
    {
        public int Age {get; private set;} 
    }
  • 您需要的不仅仅是简单的获取/设置 - 在这种情况下,您应该避免为此成员使用自动属性。
  • 您想避免通过 get 或 set 并直接使用成员的性能影响 - 在这种情况下,如果真的有性能影响,我会感到惊讶。简单的 get/set 成员非常容易内联,在我的(不可否认的)测试中,我没有发现使用自动属性和直接访问成员之间的区别。
  • 您只想拥有公共读取访问权限(即,只是一个“get”)并且类直接写入成员 - 在这种情况下,您可以在您的自动属性中使用私有集。IE

    public class MyClass
    {
        public int Age {get; private set;} 
    }

This usually covers most the reasons for wanting to directly get to the backing field used by the automatic properties.

这通常涵盖了想要直接访问自动属性使用的支持字段的大部分原因。

回答by Wedge

You shouldn't, and it's very unlikely you need to. If you need to access the property, just use the public property (e.g. this.Age). There's nothing special about the private field backing the public property, using it in preference to the property is just superstition.

你不应该,而且你不太可能需要。如果您需要访问该属性,只需使用公共属性(例如 this.Age)。支持公共财产的私有领域没有什么特别之处,优先使用它而不是财产只是迷信。