开发者

c# Convert struct to another struct

Is there any way, how to convert this:

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

I have struct in Library2.Content that has data defined same way ({ int a; int b; }), but different methods.

Is there a way to convert a struct inst开发者_StackOverflowance from Library.Content to Library2.Content? Something like:

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


You have several options, including:

  • You could define an explicit (or implicit) conversion operator from one type to the other. Note that this implies that one library (the one defining the conversion operator) must take a dependency on the other.
  • You could define your own utility method (possibly an extension method) that converts either type to the other. In this case, your code to do the conversion would need to change to invoke the utility method rather than performing a cast.
  • You could just new up a Library2.Content and pass in the values of your Library.Content to the constructor.


Just for completeness, there is another way to do this if the layout of the data types is the same - through marshaling.

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"); }
}


You could define an explicit conversion operator inside Library2.Content as follows:

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


A bit late to the game. But if the structs match I used this in the past

public static object CastTo(ref object obj, Type type)
{
    var ptr = Marshal.AllocHGlobal(Marshal.SizeOf(type));
    try
    {
        Marshal.StructureToPtr(obj, ptr, false);
        return Marshal.PtrToStructure(ptr, type);
    }
    finally
    {
        Marshal.FreeHGlobal(ptr);
    }
}

Thanks to @avi_sweden for pointing out that the allocated memory should be freed

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜