属性通过属性访问器访问,即get;set;方法
public class Person { public string FirstName; // 没有显示声明get;set;方法 }
public class Person { public string FirstName { get; set; } }
public class Person { public string FirstName { get; private set; } = "zhangsan"; }
public class Person { public string FirstName { get { return firstName; } set { firstName = value; } } private string firstName; }
public class Person { public string FirstName { get => firstName; set => firstName = value; } private string firstName; }
public class Person { public Person(string firstName) => this.FirstName = firstName; public string FirstName { get; } }
public class Person { public string FirstName { get; set; } public string LastName { get; set; } public string FullName => $"{FirstName} {LastName}"; }
public class Person { private string firstName; public string FirstName { get => firstName; set { firstName = value; fullName = null; } } private string lastName; public string LastName { get => lastName; set { lastName = value; fullName = null; } } private string fullName; public string FullName { get { if (fullName == null) fullName = $"{FirstName} {LastName}"; return fullName; } } }
public class Person { public string FirstName { get; set; } public string LastName { get; set; } [field:NonSerialized] public int Id { get; set; } public string FullName => $"{FirstName} {LastName}"; }
public class Person : INotifyPropertyChanged { public string FirstName { get => firstName; set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("First name must not be blank"); if (value != firstName) { firstName = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(FirstName))); } } } private string firstName; public event PropertyChangedEventHandler PropertyChanged; // remaining implementation removed from listing }
参考:https://docs.microsoft.com/zh-cn/dotnet/csharp/properties