2012-11-22 25 views
2

我有以下幾點:字段信息值轉換爲一個列表當列表類型不知道

[Serializable()] 
    public struct ModuleStruct { 
     public string moduleId; 
     public bool isActive; 
     public bool hasFrenchVersion; 
     public string titleEn; 
     public string titleFr; 
     public string descriptionEn; 
     public string descriptionFr; 
     public bool isLoaded; 
     public List<SectionStruct> sections; 
     public List<QuestionStruct> questions; 
    } 

我創造了這樣的一個實例,填充它(內容爲問題不相關)。我有一個函數,它將實例化的對象作爲一個參數,讓它稱爲模塊,並將此對象的類型作爲其他參數:module.GetType()

該函數將然後,使用反射,並且:

FieldInfo[] fields = StructType.GetFields(); 
    string fieldName = string.Empty; 

函數中的參數名稱和StructStructType

我循環遍歷Struct中的字段名稱,拉取值和不同字段,然後對其進行處理。一切都很好,直到我到:

public List<SectionStruct> sections; 
    public List<QuestionStruct> questions; 

功能只知道的StructStructType類型。在VB中,代碼很簡單:

Dim fieldValue = Nothing 
    fieldValue = fields(8).GetValue(Struct) 

然後:

fieldValue(0) 

得到列表部分的第一個元素;但是,在C#中,相同的代碼不起作用,因爲fieldValue是一個對象,我不能在對象上執行fieldValue[0]

那麼我的問題是,函數只知道StructTypeStruct的類型,如果可能的話,如何複製C#中的VB行爲?

+0

你想做什麼?獲取'sections'列表中的第一個對象,知道它是一個'List '? – khellang

+0

問題是,當我試圖獲取第一個元素時,我不知道類型是SectionStruct。如果我知道它是什麼,那很容易。就像我說的那樣,在VB中它非常容易,因爲它會自動將其視爲底層類型。 C#沒有,所以我需要弄清楚如何讓它像底層類型一樣處理。 – type4o

+0

但你** **知道它。只是不在編譯時;)讓我爲你修復一些示例代碼,並在同一時間,教你一些[命名約定](http://msdn.microsoft.com/en-us/library/vstudio/ms229002 (v = vs.100).aspx)... – khellang

回答

2

以下是這幾乎是拼了一些(很簡單)示例代碼...我真的不想做整個事情給你,因爲這可能是在反射:)

private void DoSomethingWithFields<T>(T obj) 
{ 
    // Go through all fields of the type. 
    foreach (var field in typeof(T).GetFields()) 
    { 
     var fieldValue = field.GetValue(obj); 

     // You would probably need to do a null check 
     // somewhere to avoid a NullReferenceException. 

     // Check if this is a list/array 
     if (typeof(IList).IsAssignableFrom(field.FieldType)) 
     { 
      // By now, we know that this is assignable from IList, so we can safely cast it. 
      foreach (var item in fieldValue as IList) 
      { 
       // Do you want to know the item type? 
       var itemType = item.GetType(); 

       // Do what you want with the items. 
      } 
     } 
     else 
     { 
      // This is not a list, do something with value 
     } 
    } 
} 
一個很大的教訓
+0

百萬感謝你@khellang。確實是一個寶貴的教訓,如此簡單。我感到很黯淡,但很開心。 – type4o

+0

偉大的,你得到它的工作!我想從VB.NET轉換到C#更難以期望;) – khellang

相關問題