获取属性值并将类类型转换为布尔值

时间:2015-11-11 10:08:58

标签: c# reflection properties getvalue

我有以下代码:

 ClassName class = new ClassName();

 var getValue = GetPrivateProperty<BaseClass>(class, "BoolProperty");

 public static T GetPrivateProperty<T>(object obj, string name)
    {
        BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
        PropertyInfo field = typeof(T).GetProperty(name, flags);
        return (T)field.GetValue(obj, null);
    }

现在,当我在return语句中得到一个InvalidCastException时,他无法将类型为System.Boolean的对象转换为ClassName类型。 BaseClass具有该属性。 ClassName继承自BaseClass。必须从&#34; ClassName&#34;访问所有属性。类。由于此属性是私有的,因此我必须直接通过BaseClass访问它。这有效,但我崩溃了,因为该属性具有返回值boolean。

谢谢!

1 个答案:

答案 0 :(得分:1)

你有T类型的属性,返回值也应该是T类型?我不相信。

也许这会有所帮助:

var getValue = GetPrivateProperty<bool>(class, "BoolProperty");

public static T GetPrivateProperty<T>(object obj, string name)
{
    BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic;
    PropertyInfo field = null;
    var objType = obj.GetType();
    while (objType != null && field == null)
    {
        field = objType.GetProperty(name, flags);
        objType = objType.BaseType;
    }

    return (T)field.GetValue(obj, null);
}

请查看<BaseClass><bool>typeof(T).GetPropertyobj.GetType().GetProperty的更改。