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

Get property value and convert class type to boolean

我有以下代码:

 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 有 属性。 Class名称继承自 BaseClass。必须访问 "ClassName" Class 中的所有属性。由于这个 属性 是私有的,我必须直接通过 BaseClass 访问它。这有效,但我崩溃了,因为 属性 具有 return 值布尔值。

谢谢!

你得到了 T 类型的 属性 并且 return 值也应该是 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 的更改。