2013-02-27 22 views
2

我有很多次考慮將類的示例轉換爲Dictionary<String, String>,其中鍵是變量名稱(類字段名稱),值是可變的當前賦值。因此,我們有一個簡單的類:通用類字段解析器使用反射字典<String,String>

public class Student 
{ 
    public String field1; 
    public Int64 field2; 
    public Double field3; 
    public Decimal field4; 

    public String SomeClassMethod1() 
    { 
     ... 
    } 
    public Boolean SomeClassMethod2() 
    { 
     ... 
    } 
    public Int64 SomeClassMethod1() 
    { 
     ... 
    } 
} 

我怎麼指望它會像:

static void Main(String[] args) 
{ 
    Student student = new Student(){field1 = "", field2 = 3, field3 = 3.0, field4 = 4.55m}; 
    Dictionary<String, String> studentInDictionary = ConvertAnyToDictionary<Student>(student); 
} 

public Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T:class 
{ 
... 
} 

如何讓它真正的任何想法?對於任何建議Thx很多。

EDIT1: 預期結果:

studentInDictionary[0] = KeyValuePair("field1", ""); 
studentInDictionary[1] = KeyValuePair("field2", (3).ToString()); 
studentInDictionary[2] = KeyValuePair("field3", (3.0).ToString()); 
studentInDictionary[3] = KeyValuePair("field4", (4.55m).ToString()); 
+0

該代碼的預期輸出是什麼? – 2013-02-27 09:06:17

+0

@Maris - 如果你仔細想想,JSON是一個字符串字典,所以你想要的東西與JSON序列化程序非常相似。所以如果你不需要它,不要重新發明輪子。 – dutzu 2013-02-27 09:07:43

+0

@Maris感謝您的編輯。看到我的回答,讓我知道它是否有幫助。 – 2013-02-27 09:17:52

回答

3

這裏是你如何能做到這:

public static Dictionary<String, String> ConvertAnyToDictionary<T>(T value) where T : class { 
    var fields = typeof(T).GetFields(); 
    var properties = typeof(T).GetProperties(); 

    var dict1 = fields.ToDictionary(x => x.Name, x => x.GetValue(value).ToString()); 
    var dict2 = properties.ToDictionary(x => x.Name, x => x.GetValue(value, null).ToString()); 

    return dict1.Union(dict2).ToDictionary(x => x.Key, x=> x.Value); 
} 

編輯:我正在用計數字段屬性那裏。如果您只能使用屬性,則可以使用dict2

您可能想看看GetFields()GetProperties()方法收到的BindingFlags參數。

+0

非常感謝。這一個工程。 – Maris 2013-02-27 10:06:10

+0

@Maris不客氣。 – 2013-02-27 10:06:55

0

您可以使用序列化已經存在的序列化(XML或JSON),也可以使用反射去做。

下面是如何獲得與反射區域的例子:

Not getting fields from GetType().GetFields with BindingFlag.Default

+0

我不認爲序列化到JSON/Xml類,然後將其反序列化到Dictionary 是一個好主意。問題不在於獲取所有字段名稱,而是將值分配給類字段的當前示例。 – Maris 2013-02-27 09:13:14

+0

@Maris我在想所得到的JSON就足夠了,你實際上需要獲得KeyValuePairs的最終形式嗎?如果是,則轉到反射路徑。獲取所有字段爲FieldInfo []並從中提取名稱和值。 – dutzu 2013-02-27 09:14:23

1
var proInfos = student.GetType().GetProperties(); 

      if(proInfos!=null) 
      { 
        Dictionary<string,string> dict= new Dictionary<string, string>(); 


      foreach (var propertyInfo in proInfos) 
      { 
       var tv = propertyInfo.GetValue(currentObj, null); 

       if(tv!=null) 
       { 
        if(dict.ContainsKey(propertyInfo.Name)) 
         continue; 

        dict.Add(propertyInfo.Name, tv.ToString()); 
       } 


       } 
      } 
+0

'Student'類不包含任何*屬性*。 – 2013-02-27 09:16:49

+0

噢,我可以添加{get; set;} – Maris 2013-02-27 09:17:11

+0

@Maris:如果您需要在模型和DTO對象之間分配值,您可以添加get和set來將字段標記爲屬性,以及爲什麼要這樣做那麼請考慮AutoMapper。 – TalentTuner 2013-02-27 09:21:55