扩展方法

来源:互联网 发布:loading windows files 编辑:程序博客网 时间:2024/05/16 19:16

public static class PropertyExtension
{
        
public static object GetValueByName(this object self, string propertyName)
        {
            
if (self == null)
            {
                
return self ;
            }
            Type t 
= self.GetType();
            PropertyInfo p 
= t.GetProperty(propertyName);
            
return p.GetValue(self, null);
        }
}

扩展方法的定义:

1.方法和所在的类必须都是静态的。

2.方法的第一个参数必须是你要扩展的那个类型。

3. 在第一个参数前面还需要有一个this关键字。

扩展方法的使用:

1.用扩展的类型对象调用此方法。

2.用静态类名调用

原创粉丝点击