日期:2014-05-16 浏览次数:21099 次
属性是一种类的成员,它的实现类似函数,访问类似字段。它的作用是提供一种灵活和安全的机制来访问,修改私有字段。所以属性必须依赖于字段。
private int dd;
public int dd
{
get{ return xx*3;}
set{ xx = value/3;}
}
没有set的属性是一种只读属性,没有get的访问器是一种只写属性。 private string name;
public string Name
{
get
{
return name != null ? name : "NA";
}
}(2) set访问器类似返回类型为void的函数,使用value的隐式参数private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}(3) 访问器的限制 private int xx;
public int sxx
{
public get { return xx; }//error
set { xx = value; }
}理解:
首先第四条最容易想到,也是很合理的,毕竟是外围的决定内部的。
其次,既然第四条可以理解,那么如果只有一个访问器的时候,访问器访问级别等同属性,如果这个时候再去指 定更加严格的访问级别,那么为何不当初在属性上指定呢?
这条理解了,那么为什么必须同时具有get,set才能添加访问修饰符就更加明确了。
推理:
接口中属性是public的,那么如果接口中只有一个get或者set的时候,我们可以在继承中指明另一个访问器的属 性。但是如果接口中同时具有get,set,那么按照派生和继承的匹配性,这时候就不能这样再指定访问器的访问限制了。
public interface ISomeInterface
{
int TestProperty
{
// No access modifier allowed here
// because this is an interface.
get;
}
}
public class TestClass : ISomeInterface
{
public int TestProperty
{
// Cannot use access modifier here because
// this is an interface implementation.
get { return 10; }
// Interface property does not have set accessor,
// so access modifier is allowed.
protected set { }
}
}
private static int counter;
public static int Counter
{
get { return counter; }
}(5)属性隐藏public class Employee
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
public class Manager : Employee
{
private string name;
// Notice the use of the new modifier:
public new string Name // use new to hide property in base class
{
get { return name; }
set { name = value + ", Manager"; }
}
}
public class Parent
{
public virtual int TestProperty
{
protected set { }
get { return 0; }
}
}
public class Kid : Parent
{
public override int TestProperty
{
protected set { }
get { return 0; }
}
}abstract class Shape
{
public abst