简体   繁体   中英

C# Optimal way of custom type conversion

For example, I have a class

public class PackageDimentionsString
{       
    public string Width { get; set; }

    public string Height { get; set; }

    public string Length { get; set; }

    public string Weight { get; set; }

}

Which I need to use in some cases and its logical (but not property types) clone which look's like this

public class PackageDimentionsDecimal
{       
    public decimal Width { get; set; }

    public decimal Height { get; set; }

    public decimal Length { get; set; }

    public decimal Weight { get; set; }
}

But they represent a single entity, so I need to cast them to each other really often. The question is: what is the optimal and cleanest way of conversion? Extension method? Property that will return the brother object? Or any other options?

Using AutoMapper (offload the work on to someone else)

using System;
using AutoMapper;

public class Program
{
    public static void Main()
    {
        var config = new MapperConfiguration(cfg => cfg.CreateMap<PackageDimentionsString, PackageDimentionsDecimal>());

        var mapper = config.CreateMapper();

        var m1 = new PackageDimentionsString
        {
            Width = "1000",
            Height = "4000",
            Length = "3302",
            Weight = "445"
        };
        var m2 = mapper.Map<PackageDimentionsString, PackageDimentionsDecimal>(m1);

        Console.WriteLine(m2.Width);
        Console.WriteLine(m2.Height);
        Console.WriteLine(m2.Length);
        Console.WriteLine(m2.Weight);
    }
}

public class PackageDimentionsString
{       
    public string Width { get; set; }

    public string Height { get; set; }

    public string Length { get; set; }

    public string Weight { get; set; }

}

public class PackageDimentionsDecimal
{       
    public decimal Width { get; set; }

    public decimal Height { get; set; }

    public decimal Length { get; set; }

    public decimal Weight { get; set; }
}

This will output:

1000
4000
3302
445

How about doing this

public class PackageDimentions
{
    public dynamic Width { get; set; }

    public dynamic Height { get; set; }

    public dynamic Length { get; set; }

    public dynamic Weight { get; set; }
}

and

var dimensionDecimal = new PackageDimentions() { Width=100.00, Height =100.00,Length =100.00, Weight =100.00};
var dimensionString = new PackageDimentions() { Width = "100.00", Height = "100.00", Length = "100.00", Weight = "100.00" };

You could do this for any types

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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