c# - 将对象映射到字典,反之亦然

标签 c# .net dictionary reflection mapping

有没有优雅快速的方法将对象映射到字典,反之亦然?

示例:

IDictionary<string,object> a = new Dictionary<string,object>();
a["Id"]=1;
a["Name"]="Ahmad";
// .....

成为

SomeClass b = new SomeClass();
b.Id=1;
b.Name="Ahmad";
// ..........

最佳答案

在两个扩展方法中使用一些反射和泛型,您可以实现这一点。

是的,其他人基本上采用了相同的解决方案,但这种方法使用的反射更少,性能更佳且可读性更强:

public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
        where T : class, new()
    {
            var someObject = new T();
            var someObjectType = someObject.GetType();

            foreach (var item in source)
            {
                someObjectType
                         .GetProperty(item.Key)
                         .SetValue(someObject, item.Value, null);
            }

            return someObject;
    }

    public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

class A
{
    public string Prop1
    {
        get;
        set;
    }

    public int Prop2
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        dictionary.Add("Prop1", "hello world!");
        dictionary.Add("Prop2", 3893);
        A someObject = dictionary.ToObject<A>();

        IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
    }
}

关于c# - 将对象映射到字典,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4943817/

相关文章:

python - 使用字典理解反转一对多映射

c# - 在 Avalonedit 上为边距着色

ios - Xcode : Compiler error Dictionary <key, 值 > 不可转换为可散列

c# - 如何在无人值守模式下截取网站截图?

c# - 我怎样才能漂亮地缩短这段 C# 代码?

c# - MVC5 : UserManager. 添加到角色 () : "Error Adding User to Role: UserId not found"?

c# - 改进我选择具有唯一值的多个 XElement 以构建列表的方式

.net - 当文件无法访问时,企业库日志记录 4.1 不会写入错误监听器

c# - CheckInGatedChanges 构建工作流中的事件位置

dictionary - 在 Elixir 中按值过滤 Map 的有效方法