使用 C# shorthand 语法时如何解决字段和属性之间的歧义?

How do I solve ambiguities between fields and properties when using C# shorthand syntax?

如果没有不匹配或完全不同名称的变量,我不知道如何使用 shorthand 语法。

字段和属性之间存在歧义,但如果我以不同的方式命名它们,我将无法使用 shorthand get;放;句法。我该如何解决这个问题?

/// <summary>
/// A customer object
/// </summary>
public class Customer
{
    // These are fields
    private string name;
    private string address;
    private string city;
    private string province;
    private string postalCode;
    private string phoneNumber;
    private string emailAddress;

    // These are properties
    public string name { get; set; }
    public string address { get; set; }
    public string city { get; set; }
    public string province { get; set; }
    public string postalCode { get; set; }
    public string phoneNumber { get; set; }
    public string emailAddress { get; set; }

    // This is a constructor
    public Customer(string Name, string Address, string City, string Province, string PostalCode, string PhoneNumber, string EmailAddress)
    {
        name = Name;                    // Cannot determine if name is field or property
        address = Address;              // Cannot determine if address is field or property
        city = City;                    // Cannot determine if city is field or property
        province = Province;            // Cannot determine if province is field or property
        postalCode = PostalCode;        // Cannot determine if postalCode is field or property
        phoneNumber = PhoneNumber;      // Cannot determine if phoneNumber is field or property
        emailAddress = EmailAddress;    // Cannot determine if emailAddress is field or property
    }
}

当你声明一个自动实现的 属性:

public string Name { get; set; } 

没有必要创建支持字段。编译器代表您为 属性 创建一个隐藏的(不可访问的)支持字段,只能 通过 属性 的 getset 访问器。你甚至不必考虑它。

因此,从您上面的代码中,只需删除自动实现的属性重复的字段。

参见:https://msdn.microsoft.com/en-us/library/bb384054.aspx

当您声明 Auto 属性 时,编译器会为您生成支持字段。

即。当你声明

public string Name { get; set; }

编译器会有类似

的代码
private string name; //Your backing Field.you don't need it manually.
 public string Name
 {
    get
    {
        return this.name;
    }
    set
    {
        this.name = value;
    }
}