□ 只读属性
public class Example
{
string name;
public string Name
{
get {return name;}
}
}
□ 只写属性
public class Example
{
string name;
public string Name
{
set {name = value;}
}
}
□ 可读可写属性
public class Example
{
string name;
public string Name
{
get {return name;}
set {name = value;}
}
}
□ 自动属性
public class Example
{
public string Name {get;set;}
}
自动只读属性:
public class Example
{
public string Name{get; private set;}
}
自动只写属性:
public class Example
{
public string Name{private get; set;}
}
□ 静态属性
静态属性对应一个静态字段,通常用在"单例模式"中。"单例模式"构造函数必须是私有的。
public class Example
{
private static Example instance = new Example();
private Example(){}
public static Example GetInstance
{
get {return instance;}
}
}
□ 抽象属性
抽象类和抽象属性。
public abstrace class Person
{
public abstract string Name{get;set;}
}
抽象属性在子类中实现。
public class Student : Person
{
private string name;
public override string Name
{
get {return name;}
set {name = value;}
}
}
□ 接口属性
public interface IPerson
{
string Name {get;set;}
}
public class Student : IPerson
{
private string name;
public string Name
{
get {return name;}
set {name = value;}
}
}