2009-06-10 58 views
1

我正在從VB移動到C#。我想循環一個集合類,這是一個數據類的集合,但我似乎無法從數據類屬性中找到實際值(找到正確的代碼來這樣做)。我有一個方法循環收集類(Contacts)並保存每條記錄(Contact)。我正在使用反射,因爲我的方法不知道它是Contacts類還是Customer類,等等。這是我在VB代碼(沖淡)C#從集合類訪問對象的屬性

Public Function SaveCollection(ByVal objCollection as Object, ByVal TableName as string, ByVal spSave as string) 

Dim objClass as Object 
Dim propInfo as PropertyInfo 

For Each objClass in objCollection 

    propInfo = objClass.GetType.GetProperty("TableFieldName") 


Next 

End Function 

我有與objClass.GetType.GetProperty( 「TableFieldName」)線

在這裏,在C#中的問題是我的C#代碼

public in SaveCollection(DictionaryBase objCollection, string TableName, string spSave) 
{ 
    PropertyInfo propInfo; 

    foreach (DictionaryEntry objClass in objCollection) 
     { 
     propInfo = objClass.GetType().GetProperty("TableFieldName") 

     } 

} 

C#代碼一直返回null。在我的本地窗口中,我可以看到objClass上類的proprities和propery的值,但我似乎想出瞭如何通過代碼訪問它。我使用DictionaryBase,因爲這似乎密切匹配,我會需要做的。我的數據類(聯繫人)有一些或多個屬性與聯繫人表的數據庫中的字段名稱相匹配。在我得到propInfo變量集後,然後設置我的SQLParameter的字段名,數據類型等,然後將值設置爲propInfo.value。

感謝您的幫助。

回答

1

你需要獲得後綴的值。還要注意GetValue返回object,然後你可以將它轉換爲字符串或者int或者任何一種你所期望的價值是。

public in SaveCollection(DictionaryBase objCollection, string TableName, string spSave) 
{ 
    PropertyInfo propInfo; 

    foreach (DictionaryEntry objClass in objCollection) 
     { 
      object tempObj = objClass.Value; 
      propInfo = tempObj.GetType().GetProperty("TableFieldName"); 

      object[] obRetVal = new Object[0]; 
      object value = propInfo.GetValue(tempObj,obRetVal); 
     } 

} 

,如果你知道TableFieldName會再串改變這一行。

string value = propInfo.GetValue(tempObj,obRetVal) as string; 
3

它看起來像你正在傳遞一個不同的集合到VB代碼和C#代碼。我的猜測是,在VB代碼中,您傳遞字典的值,並且在C#中傳遞字典本身。嘗試將C#行更改爲以下內容

propInfo = objClass.Value.GetType().GetProperty("TableFieldName"); 
+2

+1顯然DictionaryEntry沒有這樣的屬性。 – 2009-06-10 17:58:53

+2

永遠不會有,因爲它是一個結構。 (即,您將無法從DictionaryEntry中派生出具有該屬性的新類型。) – 2009-06-10 18:02:14

0

您正在查看DictionaryEntry類的屬性。不是特定鍵值對中的值的類別。考慮嘗試使用objClass.Value.GetType().GetProperty("TableFieldName")

2

我看不出你爲什麼在這裏使用字典 - 如果它只是一個集合,爲什麼不是IEnumerable實際上這裏有一個關鍵你要存儲的東西?

DictionaryEntry永遠不會有TableFieldName屬性。您確定不需要在DictionaryEntry中使用(或鍵)(使用ValueKey屬性)。

你真的需要這樣做嗎?在定義一個具有TableFieldName屬性的公共接口之後,您不能使用泛型方法嗎?例如:

public void SaveCollection<T>(IEnumerable<T> collection) 
    where T : ITableDescriptor 
{ 
    foreach (T element in collection) 
    { 
     string tableFieldName = element.TableFieldName; 
     // use the table field name here 
    } 
} 
+0

謝謝。我在大約4年前創建了我的原始VB代碼,並從此使用它。轉換時再看看它,讓我質疑爲什麼我首先使用了Reflection。 – VBCSharp 2009-06-10 18:10:09

0

也請考慮切換到泛型,如果可以的話。我想你應該能夠做這樣的事情:

VB:

Private l As List(Of MyClassName) 

C#:

private List<MyClassName> l; 

你可能不希望使用一個列表,但它只是一個例子。之後,訪問列表中每個項目的成員可以通過intellisense完成。通常,泛型可以更快,因爲您不必進行任何投射。