一开始我们的对象是这样的
public sealed class Emplyee
{
public string Name;
public int Age;
}然后为了数据不被破坏,所谓的数据封装,于是就成了这样:public sealed class Emplyee
{
private string _name;
private int _age;
public string GetName()
{
return _name;
}
public void SetName(string name)
{
this._name = name;
}
public int GetAge()
{
return _age;
}
public void SetAge(int age)
{
this._age = age;
}
}
这样还带来了一个好处就是要设置年龄时,可在SetAge(int age)加条件,屏蔽不可能情况。
public void SetAge(int age)
{
if(age < 0)
throw new ArgumentOutOfRangeException("age", age.ToString(), "the age must be greater than or equal to 0");
this._age = age;
}可是,问题来了,员工的资料内容好多,属性好多,怎么办。。。。。
东西一多,麻烦就来了
大微软说不用怕,早就给你设计好了AIP(automatically implemented property)
class Employee
{
private string _name;
private int _age;
public string Name
{
get { return (_name); }
set { _name = value; }
}
public int Age
{
get { return _age; }
set
{
if(value < 0)
throw new ArgumentOutOfRangeException("age", _age.ToString(), "the age must be greater than or equal to 0");
_age = value;
}
}
}是不是觉得略有方便。
那来说说不好的地方吧
1.任何类型只要含有一个AIP,就没办法对此类型的实例就行反序列化
2.调试时不能在AIP的set,get方法上加断点
几个注意事项:
1.属性方法可能抛异常,字段则永不会
2.属性不能作为out或ref参数传给方法,而字段可以,就像这样
class Employee
{
private string _name;
private int _age;
public string Name
{
get { return (_name); }
set { }
}
}
public class TestClass
{
void MethodWithOutParam(out string n) { n = null; }
public TestClass()
{
Employee ee = new Employee();
MethodWithOutParam(out ee.Name);
}
}机智的VS就会在ee.Name下面画出鲜红的波浪线
3.连续的调用,可能返回不同的值,因为这是方法
像那么做以后就可以这么申明对象了
Employee ee = new Employee() { Name = "jeff", Age = 45 };如果调用的本来就是无参构造器,还可以这样
Employee ee = new Employee { Name = "jeff", Age = 45 };甚至还可以这样
var ee = new { Name = "jeff", Age = 45 };当然这时的ee也就不是Employee实例对象了
还有
var people = new[]
{
new { Name = "ghost", Year = 1945 },
new { Name = "fuck", Year = 1954 },
new { Name = "damn", Year = 1938 },
};
本文详细介绍了C#中属性的使用方法及其在实际开发中的常见问题与解决策略,包括数据封装、验证机制和属性的特性等。通过实例演示了如何避免反序列化问题、调试困难以及属性调用可能导致的不确定行为,同时介绍了自动实现属性(AIP)的便利性与限制,并提供了在实际项目中高效应用属性的建议。
2882

被折叠的 条评论
为什么被折叠?



