简体   繁体   English

在C#中无法将方法内部的结构数组分配给C#?

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

Here is the code snippet from my LinqPad: 这是我的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> . 我想改变已知类型的一个对象阵列, Elephant ,对类型T的T另一个目的数组不是一个class ,但不限于struct ,其通过已经提供的存在API.And的类型T共享一些共同的属性的每个实例,表示Size ,但也有自己的特殊属性,在示例代码中已将其省略。因此,我将dynamic关键字放入Transform2AnotherType<T> And I could not even to use Dump to make sure if the assignment has made effect,thus will throw RuntimeBinderException . 而且我什至无法使用Dump来确保分配是否生效,因此将抛出RuntimeBinderException

My question is: how to correctly make the assignment in such a struct array and return it back properly? 我的问题是:如何在这样的结构数组中正确进行赋值并将其正确返回?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM