c#将struct转换为另一个struct

有什么办法,如何转换这个:

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

我在Library2.Content中有结构,其数据定义方式相同( { int a; int b; } ),但方法不同。

有没有办法将struct实例从Library.Content转换为Library2.Content? 就像是:

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

您有几种选择,包括:

  • 您可以将显式(或隐式)转换运算符从一种类型定义到另一种类型。 请注意,这意味着一个库(定义转换运算符的库)必须依赖另一个库。
  • 您可以定义自己的实用程序方法(可能是扩展方法),将任一类型转换为另一种类型。 在这种情况下,执行转换的代码需要更改为调用实用程序方法而不是执行转换。
  • 您可以只创建一个Library2.Content并将Library.Content的值传递给构造函数。

只是为了完整性,如果数据类型的布局相同 – 通过封送处理,还有另一种方法可以做到这一点。

 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(ref s3); } static T CopyStruct(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"); } } 

您可以在Library2.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 }; }