Mau*_*Mau 3 .net generics automapper automapper-3
我正在构建一个通用的漂亮打印方法.我想分开处理的一种特殊类型是KeyValuePair<TK,TV>.为了将对象缩小为已知类型,我想我会将每个映射KeyValuePair<TK,TV>到a KeyValuePair<object, object>.
下面的代码总是产生在2个空值Key,Value的性能proxy.
Mapper.CreateMap(o.GetType(), typeof(KeyValuePair<object, object>));
var proxy = Mapper.Map<KeyValuePair<object, object>>(o);
Run Code Online (Sandbox Code Playgroud)
另一方面,这个非通用版本按预期工作:
Mapper.CreateMap(o.GetType(), typeof(DictionaryEntry));
var proxy = Mapper.Map<DictionaryEntry>(o);
Run Code Online (Sandbox Code Playgroud)
为什么?
o在这个阶段已被测试为KeyValuePair<,>.
我在.NET 4.0上使用AutoMapper 3.2.1.0.
DictionaryEntry是的Key,Value都是可以设定的.映射到时DictionaryEntry,AutoMapper会匹配Key和Value属性并设置它们.
KeyValuePair<TKey, TValue>因为它是不可变的,所以无法做到这一点.因此,AutoMapper返回一个KeyValuePair<object, object>带有Key和未Value设置属性的新元素.
通常情况下,你可以用它ConstructUsing来解决这个问题:
Mapper.CreateMap<KeyValuePair<string, string>, KeyValuePair<object, object>>()
.ConstructUsing(kvp => new KeyValuePair<object, object>(kvp.Key, kvp.Value));
Run Code Online (Sandbox Code Playgroud)
但是,由于您没有使用此版本CreateMap,因此无法实现.
您可以创建一个简单的扩展方法来执行此操作:
public static class KeyValuePairExtensions
{
public static KeyValuePair<object, object> CastUp<TKey, TValue>(
this KeyValuePair<TKey, TValue> kvp)
{
return new KeyValuePair<object, object>(kvp.Key, kvp.Value);
}
}
Run Code Online (Sandbox Code Playgroud)
然后使用它而不是AutoMapper:
var kvp = new KeyValuePair<string, string>("Hello", "World");
KeyValuePair<object, object> proxy = kvp.CastUp();
Run Code Online (Sandbox Code Playgroud)
这样可以防止必须为KeyValuePair您使用的每个变体创建不同的映射定义.
| 归档时间: |
|
| 查看次数: |
2205 次 |
| 最近记录: |