2015-08-18 115 views
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; 
     } 
    } 
} 

唯一的例外是:

對象不匹配目標類型

回答

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

應該

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

你應該通過實例而不是PropertInfo本身。

+0

有趣的是,這正是消息所說的。目標類型不匹配。 – usr

相關問題