繁体   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