Assignment to struct array inside method does not

2019-09-07 02:31发布

Here is the code snippet from my LinqPad:

public class Elephant{
    public int Size;
    public Elephant()
    {
        Size = 1;
    }
}

public struct Ant{
    public int Size;
}

private  T[]  Transform2AnotherType<T>(Elephant[] elephantList)
          where T:new()
{
        dynamic tArray = new T[elephantList.Length];
        for (int i = 0; i < elephantList.Length; i++)
        {
            tArray[i] = new T();
            tArray[i].Size = 100;
                    //tArray[i].Dump();
        }

     return tArray;
}

void Main()
{
    var elephantList = new Elephant[2];
    var elephant1 = new Elephant();
    var elephant2 = new Elephant();
    elephantList[0] = elephant1;
    elephantList[1] = elephant2;
    elephantList.Dump();

    var r = Transform2AnotherType<Ant>(elephantList);
    r.Dump();
}

I want to change one object array of known type,Elephant,to another object array of type T. T is not a class,but limited to struct which provided by the already existed API.And every instance of type T shares some common property,says Size,but also has their own particular property which I have omitted in my example code.So I put dynamic keyword inside the Transform2AnotherType<T>. And I could not even to use Dump to make sure if the assignment has made effect,thus will throw RuntimeBinderException.

My question is: how to correctly make the assignment in such a struct array and return it back properly?

1条回答
聊天终结者
2楼-- · 2019-09-07 03:05

I suggest change your code like this:

public class Elephant 
    {
        public Elephant()
        {
            Size = 1;
        }

        public int Size { get; set; }
    }

    public struct Ant 
    {
        public int Size { get; set; }
    }

    private static T[] Transform2AnotherType<T>(Elephant[] elephantList)
              where T : new()
    {
        T[] tArray = new T[elephantList.Length];
        for (int i = 0; i < elephantList.Length; i++)
        {
            dynamic arrayElement = new T();
            arrayElement.Size = 100;
            tArray[i] = arrayElement;
            //tArray[i].Dump();
        }

        return tArray;
    }

    static void Main()
    {


        var elephantList = new Elephant[2];
        var elephant1 = new Elephant();
        var elephant2 = new Elephant();
        elephantList[0] = elephant1;
        elephantList[1] = elephant2;
        //elephantList.Dump();

        var r = Transform2AnotherType<Ant>(elephantList);
        //r.Dump();
    }
查看更多
登录 后发表回答