1
我有一个项目正在读取从SQL Server视图返回的行,让我们调用视图'Foo',并将这些行写入一系列文件。使用LINQ2SQL引用我的项目中的视图,Foo的结果称为'FooResults'。C#PropertyInfo GetValue()返回“对象与目标类型不匹配”
下面提供的方法接受要解析的对象的类型以及分隔符,写入文件的路径以及要解析的数据的通用列表。我已经指出抛出异常的位置。
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;
}
}
}
唯一的例外是:
对象不匹配目标类型
有趣的是,这正是消息所说的。目标类型不匹配。 – usr