通过反射访问模型 class 的布尔值并访问它们的值

Access bools of a model class through reflection and access their values

我有一个模型class:

using System;
using System.Collections.Generic;

namespace UserManagement.Models
{
    public partial class ComBox
    {
        public int FkSystem { get; set; }
        public int FkUsers { get; set; }
        public bool? Pkw { get; set; }
        public bool? Trpv { get; set; }
        public bool? Trcv { get; set; }
        public bool? Lkw { get; set; }
        public bool? Smart { get; set; }
        public bool? Itresponsible { get; set; }
        public bool? DealerPrincipalSales { get; set; }
        public bool? SalesManager { get; set; }
        public bool? SalesAdministrator { get; set; }
         .
         .
         .    
        public virtual Systems FkSystemNavigation { get; set; }
        public virtual Users FkUsersNavigation { get; set; }
    }
}

现在我必须为我生成的 PDF 文档中的每个 bool 勾选一个复选框。我的问题是:我不仅有一个模型 class,还有 30 个模型。我想自动迭代每个模型,提取布尔值并勾选一个复选框,具体取决于布尔值。

ComBox cfgItem = (ComBox)cfgList[cl.FkID];

IEnumerable<PropertyInfo> Cfg = cfgItem.GetType()
   .GetProperties()
   .Where(p => p.PropertyType == typeof(bool?));

foreach (PropertyInfo b in Cfg) 
{
   if ( (Nullable<bool>)b.GetValue(b, null) == true)                                  
      form.GetField(cl.Systemname+"_"+b.Name).SetValue("Yes");
}

对于 if 行,系统给出以下错误:

System.Reflection.TargetException HResult=0x80131603
Message=Object does not match target type.

有什么办法可以解决这个错误吗?

这一位是错误的:

b.GetValue(b, null)

b 是一个 PropertyInfo。您传递给 GetValue 的参数需要是要从中获取值的对象实例,在您的例子中是 cfgItem。您不需要传递第二个参数:

b.GetValue(cfgItem);