C#:属性

public string SomeProperty

{

// get 访问器不带参数,且必须返回属性声明的类型

get

{

return"This is the property value";

}

// set访问器也不带任何显示参数,但是编译器假定它带一个参数,其类型也与属性相同,并表示为value

set

{

// do whatever needs to be done to set the property

}

}

privatestring foreName;

publicstring ForeName

{

get

{

return foreName;

}

set

{

if (value.Length > 20)

{

// throw an exception

}

else

{

foreName = value;

}

}

}

1. 只读属性: 在属性定义中省略set访问器; 只写属性:在属性定义中省略get访问器(这是不好的编程方式)

2. 属性的访问修饰符:

使用的时候要注意以下几点:

  • 定义属性的时候,外层一定要有访问级别修饰符(public string Name
  • 在定义get和set访问级别的时候,只能为其中一个单独设置(下面例子中的get权限默认是外层的权限)
  • 外层的权限一定要比内层的更为宽松

private string _name;

public string Name

{

get

{

return _name;

}

privateset

{

_name = value;

}

}

3. 自动实现的属性:必须有两个访问器,不能把该属性设置成只读或只写属性

public string ForeName { get; set; }

public string ForeName { get; privateset; }

原文地址:https://www.cnblogs.com/LilianChen/p/2934941.html