2010-09-26 59 views
4

有什麼辦法,如何將這種轉換:C#轉換結構到另一個結構

namespace Library 
{ 
    public struct Content 
    { 
     int a; 
     int b; 
    } 
} 

我在有數據定義相同的方式 ({ int a; int b; })Library2.Content結構,但不同的方法。

有沒有辦法將一個結構實例從Library.Content轉換爲Library2.Content?喜歡的東西:

Library.Content c1 = new Library.Content(10, 11); 
Library2.Content c2 = (Libary2.Content)(c1); //this doesn't work 

回答

10

您有幾種選擇,包括:

  • 你可以從一種類型定義一個明確的(或隱含的)轉換操作符其他。請注意,這意味着一個庫(定義轉換運算符的庫)必須依賴另一個庫。
  • 您可以定義自己的實用程序方法(可能是擴展方法),將任一類型轉換爲另一種類型。在這種情況下,執行轉換的代碼需要更改爲調用實用程序方法,而不是執行轉換。
  • 您可以新建一個Library2.Content並將Library.Content的值傳遞給構造函數。
5

如下您可以定義一個明確的conversion operatorLibrary2.Content

// explicit Library.Content to Library2.Content conversion operator 
public static explicit operator Content(Library.Content content) { 
    return new Library2.Content { 
     a = content.a, 
     b = content.b 
    }; 
} 
+0

問題是,我沒有內部Library2和分享幫助我不知道Library2 – Perry 2010-09-26 17:19:43

+0

的存在,那麼去@Kent Boogaart的第二個或第三個選項的訪問。 – 2010-09-26 17:21:58

7

只是爲了保持完整性,還有另一種方式來做到這一點,如果數據類型的佈局是相同的 - 通過編組。

static void Main(string[] args) 
{ 

    foo1 s1 = new foo1(); 
    foo2 s2 = new foo2(); 
    s1.a = 1; 
    s1.b = 2; 

    s2.c = 3; 
    s2.d = 4; 

    object s3 = s1; 
    s2 = CopyStruct<foo2>(ref s3); 

} 

static T CopyStruct<T>(ref object s1) 
{ 
    GCHandle handle = GCHandle.Alloc(s1, GCHandleType.Pinned); 
    T typedStruct = (T)Marshal.PtrToStructure(handle.AddrOfPinnedObject(), typeof(T)); 
    handle.Free(); 
    return typedStruct; 
} 

struct foo1 
{ 
    public int a; 
    public int b; 

    public void method1() { Console.WriteLine("foo1"); } 
} 

struct foo2 
{ 
    public int c; 
    public int d; 

    public void method2() { Console.WriteLine("foo2"); } 
} 
+1

同樣如果你允許不安全的代碼:'foo2 s2 = *(foo2 *)&s1;' – 2017-09-26 11:25:16