我很多次考虑将类的示例转换为 Dictionary<String, String>
其中 key 是变量名称(类字段名称),value 是变量当前分配的值。所以我们有一个简单的类:
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
{
...
}
关于如何实现它有什么想法吗?非常感谢您的任何建议。
编辑1: 预期结果:
studentInDictionary[0] = KeyValuePair("field1", "");
studentInDictionary[1] = KeyValuePair("field2", (3).ToString());
studentInDictionary[2] = KeyValuePair("field3", (3.0).ToString());
studentInDictionary[3] = KeyValuePair("field4", (4.55m).ToString());
最佳答案
以下是具体操作方法:
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
参数。
关于c# - 使用反射将通用类字段解析器转换为 Dictionary<String, String>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15107909/