4

ValueInjectorを使用してクラスをフラット化し、からの値をコピーするようにしようとしていNullable<int>'sます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; }
}

CustomerIDとOrderIDが異なるタイプであるという事実を無視してCustomerObjectのインスタンスをCustomerDTOにフラット化したいと思います(1つはnull許容型であり、1つはnull許容型ではありません)。

だから私はこれをしたいと思います:

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;
    }
}

基本的には2つを組み合わせたいと思います。これは可能ですか?

4

3 に答える 3

9

これは、TypesMatch メソッドをオーバーライドすることで実行できます。

    public class MyFlatInj : FlatLoopValueInjection
    {
        protected override bool TypesMatch(Type sourceType, Type targetType)
        {
            var snt = Nullable.GetUnderlyingType(sourceType);
            var tnt = Nullable.GetUnderlyingType(targetType);

            return sourceType == targetType
                   || sourceType == tnt
                   || targetType == snt
                   || snt == tnt;
        }
    }

または、ソース コードから FlatLoopValueInjection を取得し、必要に応じて編集します (約 10 行です)。

于 2012-04-18T07:33:28.773 に答える