【问题标题】:Access bools of a model class through reflection and access their values通过反射访问模型类的布尔值并访问它们的值
【发布时间】:2020-01-16 11:16:16
【问题描述】:

我有一个模型类:

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 文档中的每个布尔值勾选一个复选框。我的问题是:我不仅有一个模型类,而且有 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-line,系统给我以下错误:

System.Reflection.TargetException HResult=0x80131603
Message=Object 与目标类型不匹配。

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

【问题讨论】:

  • 具体是哪个位引发了该错误?
  • 这是 if 子句中的演员表。

标签: c# asp.net-core razor blazor-server-side


【解决方案1】:

这一点是错误的:

b.GetValue(b, null)

bPropertyInfo。您传递给GetValue 的参数需要是从中获取值的对象实例,在您的情况下为cfgItem。您不需要传递第二个参数:

b.GetValue(cfgItem);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-09
    • 1970-01-01
    • 2016-01-18
    • 1970-01-01
    • 1970-01-01
    • 2016-01-07
    • 2022-01-11
    相关资源
    最近更新 更多