.net 无法将类型“System.Reflection.PropertyInfo”转换为“bool”

xriantvc  于 2023-06-25  发布在  .NET
关注(0)|答案(1)|浏览(83)

我正在运行时使用Activator.CreateInstance初始化类。如何循环遍历初始化的类的所有属性?我收到一个编译时错误“无法将类型'System.Reflection.PropertyInfo'转换为'bool'”

public class CustomOperations<T> where T : class
{
    public void AssignValues(int input)
    { 
        T newObject = default(T);
        newObject = Activator.CreateInstance<T>();

        foreach (PropertyInfo prop in newObject.GetType().GetProperties().ToList())
        {
            //Getting a compile time error - Cannot convert type 'System.Reflection.PropertyInfo' to 'bool'
            bool field = (bool)prop;
        }
    }
}
gwbalxhn

gwbalxhn1#

prop的类型是PropertyInfo,如果你想要newobject的实际值,你需要得到它的值。我更改了下面的代码(并添加了一个安全性,因此它只获取bool类型的属性)

public class CustomOperations<T> where T : class
{
    public void AssignValues(int input)
    { 
        T newObject = default(T);
        newObject = Activator.CreateInstance<T>();

        foreach (PropertyInfo prop in newObject.GetType().GetProperties().Where(p=>p.PropertyType == typeof(bool)).ToList())
        {
            bool field = (bool)prop.GetValue(newObject);
        }
    }
}

相关问题