2017-07-08 177 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(); 
     } 
相關問題