我以前发布过我的问题here,但我没有得到任何答复,原因-我想-这太笼统了.我会尽量简化.
我有两个相同类型的对象,我想映射一些属性并排除其他属性.我想做的是将对象保存在缓存中,以后仅使用具有特定属性的属性(字段)将其提取.
我看过Automapper,但没有找到任何适合我的东西,因此我考虑过要实现自己的系统.
我创建了一个属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class FilterFieldAttribute: Attribute
{
}
并在需要包括的字段上装饰了一个类:
public class OrdersViewModel : BaseViewModel
{
...
[FilterField]
[DisplayName("Order Number:")]
public string OrderNumber { get; set; }
[FilterField]
[DisplayName("From date:")]
public DateTime FromDate { get; set; }
[FilterField]
[DisplayName("To date:")]
public DateTime ToDate { get; set; }
[DisplayName("Status:")]
public int Status { get; set; }
...
}
现在,我实现了一个负责映射的函数:
private T Map<T>(T Source, T Destination) where T : BaseViewModel
{
if (Source == null)
{
return (Source);
}
FilterFieldAttribute filterAttribute;
foreach (PropertyInfo propInfo in typeof(T).GetProperties())
{
foreach (FilterFieldAttribute attr in propInfo.GetCustomAttributes(typeof(FilterFieldAttribute), false))
{
filterAttribute = attr as FilterFieldAttribute;
if (filterAttribute != null)
{
var value = propInfo.GetValue(Source, null);
propInfo.SetValue(Destination, value, null);
}
}
}
return (Destination);
}
现在,当我需要从缓存中获取视图模型并仅填充标有该属性的属性时,我的代码如下所示:
viewModel = Map<T>(myCache.Get(Key) as T, viewModel);
我不知道这是否是最好的选择,但这似乎是我找到的唯一方法.
任何建议,将不胜感激.
解决方法:
使用直接反射(如示例中所示)将很轻松;给出更完整的答案非常棘手,因为这取决于您是要浅克隆还是深克隆子对象.无论哪种方式,您都应该期望它涉及一些元编程和缓存-使用ILGenerator或Expression.
但是,对于惰性选项,序列化可能会有用.大量的序列化程序允许您使用属性来包括/排除特定的项目.通过序列化到内存流,倒带(.Position = 0)并反序列化,您应该只获得所选成员的深层副本.
这是一个使用Expression的示例:
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class FilterFieldAttribute: Attribute
{
public static T Clone<T>(T obj) where T : class, new()
{
return Cache<T>.clone(obj);
}
private static class Cache<T> where T : class, new()
{
public static readonly Func<T,T> clone;
static Cache()
{
var param = Expression.Parameter(typeof(T), "source");
var members = from prop in typeof(T).GetProperties()
where Attribute.IsDefined(prop, typeof(FilterFieldAttribute))
select Expression.Bind(prop, Expression.Property(param, prop));
var newObj = Expression.MemberInit(Expression.New(typeof(T)), members);
clone = Expression.Lambda<Func<T,T>>(newObj, param).Compile();
}
}
}
public class OrdersViewModel
{
[FilterField]
[DisplayName("Order Number:")]
public string OrderNumber { get; set; }
[FilterField]
[DisplayName("From date:")]
public DateTime FromDate { get; set; }
[FilterField]
[DisplayName("To date:")]
public DateTime ToDate { get; set; }
[DisplayName("Status:")]
public int Status { get; set; }
static void Main()
{
var foo = new OrdersViewModel { OrderNumber = "abc", FromDate = DateTime.Now,
ToDate = DateTime.Now, Status = 1};
var bar = FilterFieldAttribute.Clone(foo);
}
}