通过字符串名称获取静态属性的值

时间:2014-04-14 19:26:43

标签: c#

有一个很棒的帖子here提供了一种通过字符串名称获取属性值的方法:

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

目前,我正在尝试在基类中获取静态属性的值。但是,如果我尝试将BaseClass.Prop用作'src',我会得到一个空引用异常。虽然src与显式实例无关,但我试图获得的Prop值仍然存在。

是否有静态属性的解决方法?

2 个答案:

答案 0 :(得分:4)

调用src属性时,请勿发送static

 Type t = src.GetType();

 if (t.GetProperty(propName).GetGetMethod().IsStatic)
 {   
     src = null;
 }
 return t.GetProperty(propName).GetValue(src, null);

答案 1 :(得分:1)

要获取静态属性,您无法传递对象引用。要检测property-get是否为静态,请查看propertyInfo.GetGetMethod().IsStatic。这是你的GetPropValue方法:

public static object GetPropValue(object src, string propName)
{
    var propertyInfo = src.GetType().GetProperty(propName);
    if (propertyInfo.GetGetMethod().IsStatic)
        return propertyInfo.GetValue(null, null);
    else
        return propertyInfo.GetValue(src, null);
}
相关问题