简体   繁体   English

在基于接口作为契约的对象属性之间来回映射到Dictionary的最佳方法是什么?

[英]What is the best way to map from/to a Dictionary with objects properties based on an interface as contract?

I'm working on a very dynamic Silverlight Application where viewmodels are dynamic models. 我正在开发一个非常动态的Silverlight应用程序,其中视图模型是动态模型。 The WCF service returns a Response object that contains enough information (TableName property and an Dictionary[] array containing entities). WCF服务返回一个Response对象,该对象包含足够的信息(TableName属性和包含实体的Dictionary []数组)。

So, suppose I have a single entity (Dictionary) and some instance of viewmodel that is an object of any kind. 因此,假设我有一个单一的实体(Dictionary),并且有一个viewmodel实例是任何类型的对象。 The key of the dictionary serves as the property name, and obviously, the value will be used to set the property value in the viewmodel. 字典的键用作属性名称,显然,该值将用于在viewmodel中设置属性值。 I need to map values from this dictionary to values of the dynamic viewmodel and vice-versa. 我需要将字典中的值映射到动态视图模型的值,反之亦然。 In order to have some constraints on this mappings, I created interfaces to validate the values of the dictionary, so I only get/set values if the values propertynames are defined in the contract. 为了对此映射有一些限制,我创建了接口来验证字典的值,因此,只有在合同中定义了值属性名的情况下,我才获取/设置值。

I know about duck typing, dynamic proxies, object mappers, and I know how to use reflection. 我了解鸭子输入,动态代理,对象映射器,并且知道如何使用反射。

I started to searching for some tool or framework that can turn this task easy. 我开始寻找一些可以使这项工作变得容易的工具或框架。 So I've found Impromptu-Interface . 所以我找到了即兴接口 I'm trying to do this with Impromptu-interface: 我正在尝试使用即兴接口:

  public static TContract MapFromDictionary<TContract>(object bindingModel, Dictionary<string, object> data) where TContract : class {
  var proxy = new ImpromptuDictionary(data).ActLike<TContract>();
  var properties = Impromptu.GetMemberNames(proxy);
  foreach (var propertyName in properties) {
    object value = Impromptu.InvokeGet(proxy, propertyName);
    Impromptu.InvokeSet(bindingModel, propertyName, value);
  }
  return bindingModel.ActLike<TContract>();
}

Works like a charm. 奇迹般有效。

And the reverse mapping: 以及反向映射:

  public static Dictionary<string, object> MapToDictionary<TContract>(object source) where TContract : class {
  var proxy = source.ActLike<TContract>();
  var result = new Dictionary<string, object>();
  var properties = Impromptu.GetMemberNames(proxy);

  foreach (var propertyName in properties) {
    object value = Impromptu.InvokeGet(proxy, propertyName);
    result.Add(propertyName, value);
  }

  return result;
}

The question is: Is there any better way to do this ? 问题是:还有什么更好的方法吗?

You should be able to just use LINQs ToDictionary method instead of the foreach. 您应该能够只使用LINQs ToDictionary方法而不是foreach。 For a collection, it just takes a lambda that shows it how to get a key. 对于集合,只需要一个lambda即可显示如何获取密钥。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM