簡體   English   中英

如何將字段從一種結構復制到另一種結構

[英]How to copy fields from one structure to another

我有幾個輸入結構,需要將它們轉換為其他結構,以便將其傳遞給我的方法。

struct Source1
{
    public float x1;
    public float x2;
    public float x3;
}

struct Source2
{
    public float x1;
    public float x3;
    public float x2;
    public float x4;
}

struct Target
{
    public float x1;
    public float x2;
    public float x3;
}

我確信源結構具有必填字段(類型和名稱很重要),但是該字段的偏移量是未知的。 源結構也可能包含一些我不需要的額外字段。

如何將必填字段從源結構復制到目標結構。 我需要盡快做。

在C語言中,有一個非常簡單的解決此類問題的方法。

#define COPY(x, y) \
{\
x.x1 = y.x1;\
x.x2 = y.x2;\
x.x3 = y.x3;\
}

我當時在考慮獲取字段的集合,然后使用字段名稱作為鍵來獲取字段的值,但這對我來說似乎是一個很慢的解決方案。

https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-implement-user-defined-conversions-between-structs中進行測驗。

它詳細介紹了implicit operators的使用,這是要考慮的一種方法。

一些示例代碼:

using System;

namespace Test
{
    struct Source1
    {
        public float x1;
        public float x2;
        public float x3;

        public static implicit operator Target(Source1 value)
        {
            return new Target() { x1 = value.x1, x2 = value.x2, x3 = value.x3 };
        }
    }

    struct Target
    {
        public float x1;
        public float x2;
        public float x3;
    }

    public class Program
    {
        static void Main(string[] args)
        {
            var source = new Source1() { x1 = 1, x2 = 2, x3 = 3 };
            Target target = source;

            Console.WriteLine(target.x2);

            Console.ReadLine();
        }
    }
}

另一種選擇是使用AutoMapper 但是性能會變慢。

看看這個明確的演員表

這是源結構。

 public struct Source
    {
        public int X1;
        public int X2;
    }

這是目標。

 public struct  Target
    {
        public int Y1;
        public int Y2;
        public int Y3;

        public static explicit operator Target(Source source)
        {
            return new Target
            {
                Y1 = source.X1,
                Y2 = source.X2,
                Y3 = 0
            };
        }

}

轉換階段:

 static void Main(string[] args)
        {
            var source = new Source {X1 = 1, X2 = 2};
            var target = (Target) source;
            Console.WriteLine("Y1:{0} ,Y2{1} ,Y3:{2} ",target.Y1,target.Y2,target.Y3);
            Console.Read();
        }

暫無
暫無

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

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