我不知道如何使用簡寫語法,而不具有不匹配或完全不同名稱的變量。使用C#簡寫語法時,如何解決字段和屬性之間的歧義?
字段和屬性之間存在歧義,但是如果以不同的名稱命名它們,我不能使用速記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
}
}
代碼是不是不好的做法,不能創建一個支持字段? – Ben
@Ben:不是。公開暴露田地是不好的做法。但是,在設置和檢索字段沒有任何邏輯的情況下(例如,標準屬性只需設置字段並獲取字段),C#的設計人員就可以識別需要後臺字段的語法冗餘,因此已創建一個方便的簡寫,而不必在代碼中明確寫出它。如果合適,使用自動道具。編譯器給你的沒有後臺字段的錯覺是一件好事,因爲它消除了代碼中不必要的噪音。 – spender
@Ben:要清楚,自動道具**做**有後盾領域。你不需要聲明它,並且你不能訪問它,但它仍然存在。 – spender