我有一个包含3个属性A、B、C的List<CustomObject>
,现在需要将这个List转换成一个Dictionary,使结果如下:
Dictionary<string,object>
(Property name) A = Value of A
(Property name) B = Value of B
(Property name) C = Value of C
请建议...
我有一个包含3个属性A、B、C的List<CustomObject>
,现在需要将这个List转换成一个Dictionary,使结果如下:
Dictionary<string,object>
(Property name) A = Value of A
(Property name) B = Value of B
(Property name) C = Value of C
请建议...
CustomObject instance = new CustomObject();
var dict = instance.GetType().GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(instance, null));
instance.GetType()
来使其适用于任何类型,否则这将是一个相当不错的“一行代码” :) - leppie我找到了代码 :) 原始来源在这里。
static T CreateDelegate<T>(this DynamicMethod dm) where T : class
{
return dm.CreateDelegate(typeof(T)) as T;
}
static Dictionary<Type, Func<object, Dictionary<string, object>>> cache =
new Dictionary<Type, Func<object, Dictionary<string, object>>>();
static Dictionary<string, object> GetProperties(object o)
{
var t = o.GetType();
Func<object, Dictionary<string, object>> getter;
if (!cache.TryGetValue(t, out getter))
{
var rettype = typeof(Dictionary<string, object>);
var dm = new DynamicMethod(t.Name + ":GetProperties", rettype,
new Type[] { typeof(object) }, t);
var ilgen = dm.GetILGenerator();
var instance = ilgen.DeclareLocal(t);
var dict = ilgen.DeclareLocal(rettype);
ilgen.Emit(OpCodes.Ldarg_0);
ilgen.Emit(OpCodes.Castclass, t);
ilgen.Emit(OpCodes.Stloc, instance);
ilgen.Emit(OpCodes.Newobj, rettype.GetConstructor(Type.EmptyTypes));
ilgen.Emit(OpCodes.Stloc, dict);
var add = rettype.GetMethod("Add");
foreach (var prop in t.GetProperties(
BindingFlags.Instance |
BindingFlags.Public))
{
ilgen.Emit(OpCodes.Ldloc, dict);
ilgen.Emit(OpCodes.Ldstr, prop.Name);
ilgen.Emit(OpCodes.Ldloc, instance);
ilgen.Emit(OpCodes.Ldfld, prop);
ilgen.Emit(OpCodes.Castclass, typeof(object));
ilgen.Emit(OpCodes.Callvirt, add);
}
ilgen.Emit(OpCodes.Ldloc, dict);
ilgen.Emit(OpCodes.Ret);
cache[t] = getter =
dm.CreateDelegate<Func<object, Dictionary<string, object>>>();
}
return getter(o);
}
对于给定的类型:
class Foo
{
public string A {get;}
public int B {get;}
public bool C {get;}
}
(Foo f) => new Dictionary<string, object>
{
{ "A", f.A },
{ "B", f.B },
{ "C", f.C },
};
免责声明:目前查看的代码(未经测试)可能需要对值类型进行特殊处理(而不仅仅是强制转换)。让读者自己思考。