c#将struct转换为另一个struct

Per*_*rry 5 c# struct

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

namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}
Run Code Online (Sandbox Code Playgroud)

我在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
Run Code Online (Sandbox Code Playgroud)

Ken*_*art 10

您有几种选择,包括:

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


Bro*_*ass 8

只是为了完整性,如果数据类型的布局相同 - 通过编组,还有另一种方法可以做到这一点.

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"); }
}
Run Code Online (Sandbox Code Playgroud)

  • 同样,如果您允许不安全代码:`foo2 s2 = *(foo2*)&amp;s1;` (2认同)

Ber*_*ron 5

您可以在内部定义显式转换运算符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
    };
}
Run Code Online (Sandbox Code Playgroud)