2013-02-27 52 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