convert\map 一个现有的 属性 到 `IEnumerable<KeyValuePair<String, String>>`
convert\map an existing property to `IEnumerable<KeyValuePair<String, String>>`
我想 convert\map 现有对象到 IEnumerable<KeyValuePair<String, String>>
,其中给定 属性 的名称是键,给定 属性 的值是值。
我找到了这个,但这不太符合我的情况:automapper
我这样做了:
List<KeyValuePair<String, Object>> list = new List<KeyValuePair<String, Object>>();
foreach (var prop in genericType.GetType().GetProperties())
{
list.Add(new KeyValuePair<String, Object>(prop.Name, prop.GetValue(genericType, null)));
}
有没有不使用反射的方法,如果有怎么办?(genericType
是我知道的一种类型)
没有反思就没有办法做到这一点。这是我们为此使用的 ToDictionary
方法:
/// <summary>
/// Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
if (instance == null)
throw new NullReferenceException();
// if an object is dynamic it will convert to IDictionary<string, object>
var result = instance as IDictionary<string, object>;
if (result != null)
return result;
return instance.GetType()
.GetProperties()
.ToDictionary(x => x.Name, x => x.GetValue(instance));
}
我想 convert\map 现有对象到 IEnumerable<KeyValuePair<String, String>>
,其中给定 属性 的名称是键,给定 属性 的值是值。
我找到了这个,但这不太符合我的情况:automapper
我这样做了:
List<KeyValuePair<String, Object>> list = new List<KeyValuePair<String, Object>>();
foreach (var prop in genericType.GetType().GetProperties())
{
list.Add(new KeyValuePair<String, Object>(prop.Name, prop.GetValue(genericType, null)));
}
有没有不使用反射的方法,如果有怎么办?(genericType
是我知道的一种类型)
没有反思就没有办法做到这一点。这是我们为此使用的 ToDictionary
方法:
/// <summary>
/// Gets all public properties of an object and and puts them into dictionary.
/// </summary>
public static IDictionary<string, object> ToDictionary(this object instance)
{
if (instance == null)
throw new NullReferenceException();
// if an object is dynamic it will convert to IDictionary<string, object>
var result = instance as IDictionary<string, object>;
if (result != null)
return result;
return instance.GetType()
.GetProperties()
.ToDictionary(x => x.Name, x => x.GetValue(instance));
}