开发者

Array element to struct constrained method

开发者 https://www.devze.com 2023-03-15 06:01 出处:网络
I need to pass value from array to method that has where T : struct generic constraint. I have object[] values; That for example contains { (int)7, (byte)3, (char)\'a\' } (i don\'t know structure at

I need to pass value from array to method that has where T : struct generic constraint.

I have object[] values; That for example contains { (int)7, (byte)3, (char)'a' } (i don't know structure at compile time)

and i need to pass that array, or all elements one by one to any of following methods

DataStrea开发者_如何学运维m(Array array)
DataStream(IntPtr ptrToArray, int sizeInbytes)

DataStream.Write<T>(T value) where T : struct
DataStream.WriteBytes(byte[] bytes)

First method will write some error in GCHandle.Alloc (that object does not contain primitive data) Third mthod will not compile since object is not struct

Actual problem is that i am trying to create MeshBuilder in SlimDX that will contain VertexChannels and then build VertexBuffer out of them


Well, your array will contain boxed values which is why the first two will fail. You're not going to be able to do this all in one call.

Options:

  • Call the generic Write method using reflection, picking up the execution-time type of the values that way:

    // You may well need to do more work here, if DataStream.Write is
    // overloaded.
    MethodInfo genericMethod = typeof(DataStream).GetMethod("Write");
    foreach (object value in values)
    {
        Type type = value.GetType();
        MethodInfo method = genericMethod.MakeGenericMethod(type);
        method.Invoke(dataStream, value);
    }
    
  • Use dynamic typing if you're using C# 4 and .NET 4:

    foreach (dynamic value in values)
    {
        dataStream.Write(value);
    }
    
  • Explicitly check each value against your supported types:

    foreach (object value in values)
    {
        if (value is char)
        { 
            dataStream.Write((char) value);
        }
        else if (value is byte)
        {
            dataStream.Write((byte) value);
        }
        else if (value is int)
        {
            dataStream.Write((int) value);
        }
        else
        {
            throw new ArgumentException("Unsupported type in input data");
        }
    }
    

All of these are likely to be fairly slow, to be honest. The first is likely to be the slowest, but I wouldn't like to bet on anything without testing it first.

0

精彩评论

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