public class MyClass{// this is a field. It is private to your class and stores the actual data.private string _myField;
// this is a property. When accessed it uses the underlying field,// but only exposes the contract, which will not be affected by the underlying fieldpublic string MyProperty{get{return _myField;}set{_myField = value;}}
// This is an AutoProperty (C# 3.0 and higher) - which is a shorthand syntax// used to generate a private field for youpublic int AnotherProperty { get; set; }}
public class Person{private string _name;
public string Name{get{return _name;}set{_name = value;}}public int Age{get;set;} //AutoProperty generates private field for us}
public class Person {private string _name;
public event EventHandler NameChanging;public event EventHandler NameChanged;
public string Name{get{return _name;}set{OnNameChanging();_name = value;OnNameChanged();}}
private void OnNameChanging(){NameChanging?.Invoke(this,EventArgs.Empty);}
private void OnNameChanged(){NameChanged?.Invoke(this,EventArgs.Empty);}}
class Employee{// Private Fields for Employeeprivate int id;private string name;
//Property for id variable/fieldpublic int EmployeeId{get{return id;}set{id = value;}}
//Property for name variable/fieldpublic string EmployeeName{get{return name;}set{name = value;}}}
class MyMain{public static void Main(string [] args){Employee aEmployee = new Employee();aEmployee.EmployeeId = 101;aEmployee.EmployeeName = "Sundaran S";}}
public class DataTable{public class Rows{private string _count;
// This Count will be accessable to us but have used only "get" ie, readonlypublic int Count{get{return _count;}}}
public class Columns{private string _caption;
// Used both "get" and "set" ie, readable and writablepublic string Caption{get{return _caption;}set{_caption = value;}}}}
public class Rows{private string _count;
public int Count{get{return CalculateNoOfRows();}}
public int CalculateNoOfRows(){// Calculation here and finally set the value to _countreturn _count;}}
// A simple examplepublic class student{public int ID;public int passmark;public string name;}
public class Program{public static void Main(string[] args){student s1 = new student();s1.ID = -101; // here ID can't be -ves1.Name = null ; // here Name can't be null}}
现在我们以get和set方法为例
public class student{private int _ID;private int _passmark;private string_name ;// for id propertypublic void SetID(int ID){if(ID<=0){throw new exception("student ID should be greater then 0");}this._ID = ID;}public int getID(){return_ID;}}public class programme{public static void main(){student s1 = new student ();s1.SetID(101);}// Like this we also can use for Name propertypublic void SetName(string Name){if(string.IsNullOrEmpty(Name)){throw new exeception("name can not be null");}this._Name = Name;}public string GetName(){if( string.IsNullOrEmpty(This.Name)){return "No Name";}else{return this._name;}}// Like this we also can use for Passmark propertypublic int Getpassmark(){return this._passmark;}}
Using Getter and Setter
// fieldprivate int _age;
// setterpublic void set(int age){if (age <=0)throw new Exception();
this._age = age;}
// getterpublic int get (){return this._age;}
Now using property we can do the same thing. In the value is a key word
private int _age;
public int Age{get{return this._age;}
set{if (value <= 0)throw new Exception()}}
自动实现属性如果我们不在get和set访问器中使用逻辑,我们可以使用自动实现属性。
当use自动实现的属性编译创建一个私有的匿名字段时,只能通过get和set访问。
public int Age{get;set;}
抽象属性抽象类可能有一个抽象属性,应该在派生类中实现
public abstract class Person{public abstract string Name{get;set;}public abstract int Age{get;set;}}
// overriden something like this// Declare a Name property of type string:public override string Name{get{return name;}set{name = value;}}
我们可以私自设置一个属性在这里,我们可以私下设置自动属性(在类中设置)
public int MyProperty{get; private set;}
您可以使用此代码实现相同的目的。在此属性设置功能不可用,因为我们必须直接将值设置为字段。
private int myProperty;public int MyProperty{get { return myProperty; }}
class Room {public string sectionOne;public string sectionTwo;}
Room r = new Room();r.sectionOne = "enter";
人们很容易进入第一区,没有任何检查
class Room{private string sectionOne;private string sectionTwo;
public string SectionOne{get{return sectionOne;}set{sectionOne = Check(value);}}}
Room r = new Room();r.SectionOne = "enter";
class PropertyEmulation{private string MSomeValue;
public string GetSomeValue(){return(MSomeValue);}
public void SetSomeValue(string value){MSomeValue=value;}}
class OneHundredFields{public int Field1;public int Field2;...public int Field100;}
OneHundredFields Instance=new OneHundredFields() // Variable 'Instance' consumes 100*sizeof(int) bytes of memory.
class OneHundredProperties{public int Property1{get{return(1000);}set{// Empty.}}
public int Property2{get{return(1000);}set{// Empty.}}
...
public int Property100{get{return(1000);}set{// Empty.}}}
OneHundredProperties Instance=new OneHundredProperties() // !!!!! Variable 'Instance' consumes 0 bytes of memory. (In fact a some bytes are consumed becasue every object contais some auxiliarity data, but size doesn't depend on number of properties).
class Name{public string FullName;public int YearOfBirth;public int Age;}
Name name=new Name();
name.FullName="Tim Anderson";name.YearOfBirth=1979;name.Age=40;
class Name{private string MFullName="";private int MYearOfBirth;
public string FullName{get{return(MFullName);}set{if (value==null){throw(new InvalidOperationException("Error !"));}
MFullName=value;}}
public int YearOfBirth{get{return(MYearOfBirth);}set{if (MYearOfBirth<1900 || MYearOfBirth>DateTime.Now.Year){throw(new InvalidOperationException("Error !"));}
MYearOfBirth=value;}}
public int Age{get{return(DateTime.Now.Year-MYearOfBirth);}}
public string FullNameInUppercase{get{return(MFullName.ToUpper());}}}
class MyList{private string[] MBuffer;
public MyList(){MBuffer=new string[100];}
public string this[int Index]{get{return(MBuffer[Index]);}set{MBuffer[Index]=value;}}}
MyList List=new MyList();
List[10]="ABC";Console.WriteLine(List[10]);
由于C#3.0允许您定义自动属性。这是一个例子。
class AutoProps{public int Value1{get;set;}
public int Value2{get;set;}}
internal class AutoProps{[CompilerGenerated][DebuggerBrowsable(DebuggerBrowsableState.Never)]private int <Value1>k__BackingField;
[CompilerGenerated][DebuggerBrowsable(DebuggerBrowsableState.Never)]private int <Value2>k__BackingField;
public int Value1{[CompilerGenerated]get{return <Value1>k__BackingField;}[CompilerGenerated]set{<Value1>k__BackingField = value;}}
public int Value2{[CompilerGenerated]get{return <Value2>k__BackingField;}[CompilerGenerated]set{<Value2>k__BackingField = value;}}}