有什么办法,如何转换这个:
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给构造函数.只是为了完整性,如果数据类型的布局相同 - 通过编组,还有另一种方法可以做到这一点.
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)
您可以在内部定义显式转换运算符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)
| 归档时间: |
|
| 查看次数: |
7609 次 |
| 最近记录: |