c#将struct转换为另一个struct

时间:2010-09-26 17:10:01

标签: c# 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

3 个答案:

答案 0 :(得分:10)

您有多种选择,包括:

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

答案 1 :(得分: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"); }
}

答案 2 :(得分:5)

您可以在Library2.Content内定义明确的conversion operator,如下所示:

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