c#-3.0 - C# 3.0 :Automatic Properties - what would be the name of private variable created by compiler

标签 c#-3.0 automatic-properties

我在检查 .NET 3.5 的新特性,发现在 C# 3.0 中,我们可以使用

public class Person 
{    
 public string FirstName  { get; set; }
 public string LastName  { get; set; }
}

代替
private string name;

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

如果我使用自动属性,Name 的私有(private)变量名称是什么?互联网上的教程说编译器会自动创建一个私有(private)变量。那么我如何使用/访问私有(private)变量,如果我想在这个类的方法中使用它?

最佳答案

如前所述:您无法访问自动生成的变量(不使用坏技巧)。但是我假设您问这个问题是因为您只想拥有一个 setter/getter ,但仍想使用自动属性……对吗?在这种情况下,您可以使用这个:

public string FirstName  { get; private set; }

现在你有了一个私有(private)的 setter 和一个公共(public)的 getter。

关于c#-3.0 - C# 3.0 :Automatic Properties - what would be the name of private variable created by compiler,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1277018/

相关文章:

c# - 提高语音检测算法的准确性

asp.net - 如何在 razor 代码块中包含 ul 标签?

c# - 规范中是否实现了自动属性?

C# 3.0 自动属性——有用还是没用?

c# - 自动属性和结构

c# - 自动属性必须同时定义 get 和 set 访问器是否存在技术原因

C# 3.0,对象初始化器和获取属性返回数组,如何初始化?

c# - CLR 如何处理 C# 中的外部方法调用

c# - .NET - 如何创建一个类,以便只有一个其他特定类可以实例化它?

python - 如何使用列名+文件名格式自动重命名 python Dataframe 的列