我正在尝试使用 ValueInjector 来展平一个类,并让它也跨值从Nullable<int>'s
to复制int
。
例如,给定以下(人为的)类:
class CustomerObject
{
public int CustomerID { get; set; }
public string CustomerName { get; set; }
public OrderObject OrderOne { get; set; }
}
class OrderObject
{
public int OrderID { get; set; }
public string OrderName { get; set; }
}
class CustomerDTO
{
public int? CustomerID { get; set; }
public string CustomerName { get; set; }
public int? OrderOneOrderID { get; set; }
public string OrderOneOrderName { get; set; }
}
我想将 CustomerObject 的一个实例展平为一个 CustomerDTO,它忽略了 CustomerID 和 OrderID 是不同类型的事实(一个是可以为空的,一个不是)。
所以我想这样做:
CustomerObject co = new CustomerObject() { CustomerID = 1, CustomerName = "John Smith" };
co.OrderOne = new OrderObject() { OrderID = 2, OrderName = "test order" };
CustomerDTO customer = new CustomerDTO();
customer.InjectFrom<>(co);
然后填充所有属性,特别是:
customer.CustomerID
customer.OrderOneOrderID
customer.OrderOneOrderName
我意识到我可以FlatLoopValueInjection
用来展平对象,并且我正在使用这个 NullableInjection 类:
public class NullableInjection : ConventionInjection
{
protected override bool Match(ConventionInfo c)
{
return c.SourceProp.Name == c.TargetProp.Name &&
(c.SourceProp.Type == c.TargetProp.Type
|| c.SourceProp.Type == Nullable.GetUnderlyingType(c.TargetProp.Type)
|| (Nullable.GetUnderlyingType(c.SourceProp.Type) == c.TargetProp.Type
&& c.SourceProp.Value != null)
);
}
protected override object SetValue(ConventionInfo c)
{
return c.SourceProp.Value;
}
}
基本上我想将两者结合起来。这可能吗?