我有很多次考虑将类的示例转换为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());
该代码的预期输出是什么? – 2013-02-27 09:06:17
@Maris - 如果你仔细想想,JSON是一个字符串字典,所以你想要的东西与JSON序列化程序非常相似。所以如果你不需要它,不要重新发明轮子。 – dutzu 2013-02-27 09:07:43
@Maris感谢您的编辑。看到我的回答,让我知道它是否有帮助。 – 2013-02-27 09:17:52