简体   繁体   English

在什么情况下,不会为C#中的公共属性生成私有变量?

[英]In what cases are private variables not generated for public properties in C#?

I am specifying a public property in C# like this: 我在C#中指定这样的公共属性:

public bool SuezCanalTransversal {get; set;}

However, it appears that no private member variable is created. 但是,似乎没有创建私有成员变量。 For example, if I override the get, and return _suezCanalTransversal; 例如,如果我重写get,并return _suezCanalTransversal; I see that: 我看到:

"_suezCanalTransversal does not exist in the current context" . "_suezCanalTransversal does not exist in the current context"

It is no problem to simply add the associated private member variables on my own, but I was under the impression that this was now done automatically. 只需自己添加关联的私有成员变量是没有问题的,但是我感到这是现在自动完成的印象。

A few questions: 几个问题:

When are private member variables automatically generated for public properties and when are they not? 何时为公共属性自动生成私有成员变量,何时不生成私有成员变量?

When a public property such as public bool SuezCanalTransversal{ get; set;} 当诸如public bool SuezCanalTransversal{ get; set;} public bool SuezCanalTransversal{ get; set;} is used, is it correct to assume a private variable: private bool _suezCanalTransversal will be created? public bool SuezCanalTransversal{ get; set;} ,是否正确假设一个私有变量:将创建private bool _suezCanalTransversal

The compiler generates the backing variable, and you can not rely on any naming convention or pattern that is used to name that backing variable. 编译器生成后备变量,并且您不能依赖于用于命名该后备变量的任何命名约定或模式。

The backing variable is only declared at compile time, so you cannot access it in your source code. 支持变量仅在编译时声明,因此您无法在源代码中访问它。

If you want to have access to the backing variable, there is only one solution: do not use automatic properties, but declare the properties 'old skool', like this: 如果要访问后备变量,则只有一种解决方案:不使用自动属性,而是将属性声明为“ old skool”,如下所示:

private int _suezCanalTransversal;

public int SuezCanalTransversal
{
   { get return _suezCanalTransversal; }
   { set _suezCanalTransversal = value; }
}

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

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