2017-07-08 179 views
0

我有几个输入结构,我需要转换为其他结构,所以我可以将它传递给我的方法。如何从一个结构复制字段到另一个

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

我想买一台字段的集合,然后使用它的名字作为一个键时,会字段的值,但它看起来像慢的解决方案给我。

回答

2

https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/how-to-implement-user-defined-conversions-between-structs有一个squiz。

它详细介绍了使用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虽然性能会更慢。

+0

链接死,死链接起不到任何一个。 –

+0

@mjwills:看起来我需要为每个源结构编写运算符,对吧?假设我有五个来源和一百个字段。 – walruz

+0

查看最后一行@walruz。 – mjwills

0

看这个明确的转换

这是源结构。

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(); 
     } 
相关问题