C#PropertyInfo GetValue()返回"对象与目标类型不匹配"

And*_*ans 1 c# generics getvalue

我有一个项目正在读取从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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

例外是:

对象与目标类型不匹配

Meh*_*taş 8

var value = pinfo.GetValue(pinfo, null);
Run Code Online (Sandbox Code Playgroud)

应该

var value = pinfo.GetValue(d, null);
Run Code Online (Sandbox Code Playgroud)

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