我经常需要写一些根据对象属性名字来判断这个对象是否有这个属性或者根据属性名获取该属性的值
public static class PropertyExtension
{
public static object GetValueByName(this Person self,string propertyName)
{
if (self == null)
{
return self;
}
Type t = self.GetType();
PropertyInfo p = t.GetProperty(propertyName);
return p.GetValue(self, null);
}
}
扩展方法规定类必须是一个静态类,里面包含的所有方法都必须是静态方法
public class Person
{
private string id;
public string Id
{
get { return id; }
set { id = value; }
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public string Say()
{
return "我是中国人";
}
}
protected void Page_Load(object sender, EventArgs e)
{
Person p = new Person {Id="1",Name="wuyulong" };
string s=p.GetValueByName("Id").ToString();
Response.Write(s);
}
在扩展的时候也不要对比较高层的类进行扩展,一经扩展,所有的类都被“污染”了。
以上是我对扩展方法理解及使用,如有不对或不足的地方请多多指正,谢谢啦。。