c#将结构转换为另一个结构

c#将结构转换为另一个结构,c#,struct,C#,Struct,有没有办法,如何转换: namespace Library { public struct Content { int a; int b; } } 我在Library2.Content中有一个struct,它以同样的方式定义了数据 ({inta;intb;}),但方法不同 有没有办法将结构实例从Library.Content转换为Library2.Content?比如: Library.Content c1 = new Library.C

有没有办法,如何转换:

namespace Library
{
    public struct Content
    {
        int a;
        int b;
    }
}
我在Library2.Content中有一个struct,它以同样的方式定义了数据 (
{inta;intb;}
),但方法不同

有没有办法将结构实例从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
    的值传递给构造函数

您可以在
库2.内容中明确定义如下:

// 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
    };
}

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

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"); }
}
static void Main(字符串[]args)
{
foo1 s1=新的foo1();
foo2 s2=新的foo2();
s1.a=1;
s1.b=2;
s2.c=3;
s2.d=4;
对象s3=s1;
s2=复制结构(参考s3);
}
静态T CopyStruct(参考对象s1)
{
GCHandle handle=GCHandle.Alloc(s1,GCHandleType.pinted);
T typedStruct=(T)Marshal.PtrToStructure(handle.addrofpindedObject(),typeof(T));
handle.Free();
返回类型结构;
}
结构foo1
{
公共INTA;
公共int b;
public void method1(){Console.WriteLine(“foo1”);}
}
结构foo2
{
公共INTC;
公共int d;
public void method2(){Console.WriteLine(“foo2”);}
}

问题是,我无法访问Library2内部,在Library1中,我不知道Library2是否存在。请选择@Kent Boogaart的第二个或第三个选项。同样,如果您允许不安全的代码:
foo2 s2=*(foo2*)&s1哈哈,我正打算写同样的东西:)