不确定这是否可能,但有没有办法做到这一点?
给定这个类:
class A
{
public String B {get;set;}
public String C {get;set;}
public String D {get;set;}
}
实例化 A 并将 V1,V2,V3 分别分配给 B,C,D
我想要一个 Dictionary\Matrix\一些其他结构包含
B:V1
C:V2
D:V3
最好不使用 3rd 方库
var props = typeof(A).GetProperties();
Dictionary<string, string> output=new Dictionary<string,string>();
foreach(PropertyInfo pi in props)
{
var name = pi.Name,
string value= pi.GetValue(this, null) as string;
output[name]=value;
}
var a = new A{B = "V1", C = "V2", D = "V3"};
var dictionary = a.GetType()
.GetProperties()
.ToDictionary(prop => prop.Name,
prop => prop.GetValue(a));
字段及其值的简单示例(对于公共字段):
var a = new A("a", "b", "c");
var fields = typeof(A).GetFields();
var dict = new Dictionary<string, string>(fields.Length);
foreach (var fieldInfo in fields)
{
dict.Add(fieldInfo.Name, (string)fieldInfo.GetValue(a));
}