C# PropertyInfo GetValue() returns "Object does not match target type"

C# PropertyInfo GetValue() returns "Object does not match target type"

我有一个项目正在读取从 SQL 服务器视图返回的行,让我们调用视图 '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;
        }
    }
}

例外情况是:

Object does not match target type

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

应该是

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

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