将现有属性转换为`IEnumerable <keyvaluepair <string,string =“”>&gt;`

时间:2016-04-14 11:58:35

标签: c# automapper

我想将现有对象转换为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是我知道的类型)

1 个答案:

答案 0 :(得分:1)

没有反思就没有办法做到这一点。以下是我们用于此的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));
}