C# PropertyInfo GetValue() 返回 "Object does not match target type"。

3
我有一个项目,需要读取从SQL Server视图返回的行,我们称之为“Foo”,并将这些行写入一系列文件。在我的项目中使用LINQ2SQL引用视图,来自Foo的结果称为“FooResults”。
下面提供的方法接受要解析的对象类型、分隔符、写入文件的路径以及要解析的数据的通用列表。我已经指出了异常抛出的位置。
public void WriteRecords<T>(T classType, string delimiter, string outputPath, List<T> data)
{
    // Extract the property names and format as a delimited string
    var properties = classType.GetType().GetProperties().ToList();
    var headerLine = string.Join(delimiter, properties.Select(p => p.Name).ToArray());
    var formattedHeaderLine = new[] { headerLine };

    // Foreach line in the data provided, extract the values and format as delimited string
    foreach (var d in data)
    {
        try
        {
            foreach (var pinfo in d.GetType().GetProperties())
            {
                // This is the line causing the problems
                var value = pinfo.GetValue(pinfo, null);
            }
        }
        catch (Exception ex)
        {
            var message = ex.Message;
        }
    }
}

异常情况如下:

对象与目标类型不匹配

1个回答

12
var value = pinfo.GetValue(pinfo, null);

应该是这样的

var value = pinfo.GetValue(d, null);

你应该传递实例而不是 PropertInfo 本身。


有趣的是,这正是消息所说的。目标类型不匹配。 - usr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接