Assignment to struct array inside method does not work in C#?

折月煮酒 提交于 2019-12-25 05:59:37

问题


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:


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


来源:https://stackoverflow.com/questions/22739078/assignment-to-struct-array-inside-method-does-not-work-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!