将列入字典
我有一个List
,它有3个属性A,B,C,我需要的是将这个List转换为Dictionary,结果看起来像
Dictionary (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));
我找到了代码:)最初来自这里 。
static T CreateDelegate(this DynamicMethod dm) where T : class { return dm.CreateDelegate(typeof(T)) as T; } static Dictionary>> cache = new Dictionary>>(); static Dictionary GetProperties(object o) { var t = o.GetType(); Func
对于给定类型:
class Foo { public string A {get;} public int B {get;} public bool C {get;} }
它产生的代理相当于:
(Foo f) => new Dictionary { { "A", fA }, { "B", fB }, { "C", fC }, };
免责声明:现在查看代码(未经测试)可能需要对valuetypes(而不仅仅是castclass)进行特殊处理。 为读者锻炼。
如果我理解你想要做什么,你必须在CustomObject上使用reflrecion来获取属性名称,然后只需创建字典:
dic.add(propertyName,value);