簡體   English   中英

C#自定義類型轉換的最佳方法

[英]C# Optimal way of custom type conversion

例如,我有一堂課

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

但是它們代表一個單一的實體,因此我需要經常將它們相互轉換。 問題是:什么是最佳,最干凈的轉換方式? 擴展方法? 會返回兄弟對象的屬性? 還是其他選擇?

使用AutoMapper(將工作分擔給其他人)

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

這將輸出:

1000
4000
3302
445

怎么樣

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

    public dynamic Height { get; set; }

    public dynamic Length { get; set; }

    public dynamic Weight { get; set; }
}

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

您可以針對任何類型的對象執行此操作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM