.net 属性信息.GetValue()会掷回:对象与目标类型不匹配

hrirmatl  于 2022-11-19  发布在  .NET
关注(0)|答案(1)|浏览(131)

我想读取每个row的所有值

internal class ExcelTable<T> : IExcelTable where T : IExcelTableRow
{
    void Foo(){
        var props = typeof(T).GetProperties().ToList();
        for (int r = 0; r < Rows.Count; r++)
        {
            IExcelTableRow row = Rows[r];
            foreach (var p in props)
            {
                // Throws error on the first prop = {Int32 Id}
                var v = p.GetValue(row); 
            }
        }
    }
}

但它抛出以下错误
System.Reflection.TargetException:'对象与目标类型不匹配'
T的类型为IExcelTableRow,实现为ExcelTranscationLogRow。它在第一行上引发错误,该行具有以下值

internal class ExcelTranscationLogRow : IExcelTableRow
{
    public int Id { get; set; }                         // 3619     
    public TransactionType TransactionType { get; set; }// TransactionType.Execution
    public string Identifier { get; set; }              // "Placeholder"
    public TransactionStatus Status { get; set; }       // LogType.Success
    public LogType LogType { get; set; }                // TransactionStatus.Trace
    public string Log { get; set; }                     // "Getting KOT and CPR"
    public DateTime TimeStamp { get; set; }             // {05-07-2022 19:06:38}
}

它适用于IExcelTableRow的其他实现,例如

internal class ExcelTransactionRow : IExcelTableRow
{
    public int Id { get; set; }
    public string Identifier { get; set; }
    public TransactionStatus Status { get; set; }
    public DateTime StartTime { get; set; }
    public DateTime? EndTime { get; set; }
}
dauxcl2d

dauxcl2d1#

如果每一行都可以是不同的类型,那么您需要将props的赋值移到行循环中,并为每一行赋值。
未经测试的示例:

internal class ExcelTable : IExcelTable
{
    void Foo()
    {
        for (int r = 0; r < Rows.Count; r++)
        {
            IExcelTableRow row = Rows[r];
            var props = row.GetType().GetProperties().ToList();
            foreach (var p in props)
            {
                // Throws error on the first prop = {Int32 Id}
                var v = p.GetValue(row); 
            }
        }
    }
}

相关问题