private int test1 = 0; public int Test1 { get { return test1; } }这就是只读 在外面只能获取Test1,而不能对Test1进行写操作
还可以通过属性控制写入的值 private int num; //只读属性 public int Num { get { return this.num; } } private string str; //只写属性 public string Str { set { this.str = value; } } private double doub; //读写属性 public double Doub { get { return this.doub; } set { //有条件的写,如果大于0,返回value,否则返回0 if (value >= 0) { this.doub = value; } else { this.doub = 0; } } }
public class A { public A() {}int id; public int ID { get {return id;} } } public class B { int n; public B() { A a=new A(); n=a.ID;//正确,因为a.ID有get,可以获取。 a.ID=2;//错误,因为a.ID没有set,不能写入。 } } 所以,属性主要是对于外部而言(当然类内部也能使用),没有get的就不能获取,所以就是只写;没有set的就不能写入,所以就是只读,有get有set,就是可写可读了。
class A { int i=0; public int I { get { return i; } set { i=value; } } }class test { A a=new A(); a.I=5; Console.Write(a.I); }
誰說的set和get方法其實就是屬性?
private string property; public string Property { get{return property;} set {property=value} }get和set就是兩個方法,編譯後會分別成為get_Property和set_Property。 property是private限定,所以無法在外部訪問 而Property這個屬性,是根據get和set的設置來調用get_Property或set_Property進行讀取或賦值。 如果沒有定義set,就無從賦值,所以起到了衹讀的效果。
public int Test1
{
get
{
return test1;
}
}这就是只读
在外面只能获取Test1,而不能对Test1进行写操作
private int num;
//只读属性
public int Num
{
get { return this.num; }
} private string str;
//只写属性
public string Str
{
set { this.str = value; }
} private double doub;
//读写属性
public double Doub
{
get { return this.doub; }
set
{
//有条件的写,如果大于0,返回value,否则返回0
if (value >= 0)
{
this.doub = value;
}
else
{
this.doub = 0;
}
} }
public class A
{
public A()
{}int id;
public int ID
{
get {return id;}
}
}
public class B
{
int n;
public B()
{
A a=new A();
n=a.ID;//正确,因为a.ID有get,可以获取。
a.ID=2;//错误,因为a.ID没有set,不能写入。
}
}
所以,属性主要是对于外部而言(当然类内部也能使用),没有get的就不能获取,所以就是只写;没有set的就不能写入,所以就是只读,有get有set,就是可写可读了。
{
int i=0;
public int I
{
get
{
return i;
}
set
{
i=value;
}
}
}class test
{
A a=new A();
a.I=5;
Console.Write(a.I);
}
private string property;
public string Property
{
get{return property;}
set {property=value}
}get和set就是兩個方法,編譯後會分別成為get_Property和set_Property。
property是private限定,所以無法在外部訪問
而Property這個屬性,是根據get和set的設置來調用get_Property或set_Property進行讀取或賦值。
如果沒有定義set,就無從賦值,所以起到了衹讀的效果。