2

我有很多次考虑将类的示例转换为Dictionary<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
{
...
}

关于如何使它成为现实的任何想法?非常感谢任何建议。

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());
4

3 回答 3

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.

您可能想看一下and方法BindingFlags接收到的参数。GetFields()GetProperties()

于 2013-02-27T09:13:52.230 回答
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());
                 }


                }
             }
于 2013-02-27T09:14:48.713 回答
0

您可以使用现有的序列化程序(Xml 或 JSON)进行序列化,也可以使用反射进行序列化。

以下是如何通过反射获取字段的示例:

未使用 BindingFlag.Default 从 GetType().GetFields 获取字段

于 2013-02-27T09:09:39.200 回答