【问题标题】:How to get type of an object and then create array of objects with this type [closed]如何获取对象的类型,然后创建具有这种类型的对象数组[关闭]
【发布时间】:2013-09-05 19:25:12
【问题描述】:
class baker: unit {}
class killer: unit{}

void Round(unit first, unit second, byte fA, byte sA)
{

    how to create array of "unit first" type objects?  

}

我将面包师或杀手作为参数传递,我想在方法中克隆这个特定的类,但我不明白如何

【问题讨论】:

    标签: c# arrays types


    【解决方案1】:

    对于简单的方法:

    if(first is baker)
    {
    // Create array of bakers
    }
    

    或者你可以像这样使用泛型:

    void Round<T>(T first, T second,...)
    {
    // Create the list of the type
    new List<T>();
    

    或者你可以使用:

    Array.CreateInstance(first.GetType(), length);
    

    在最坏的情况下,您可以使用 first.GetType() 并使用反射来创建一个数组。 但它有点复杂

    【讨论】:

    • 谢谢,最后一种方法正是我要找的!
    • 在第二种方法中,如果你真的想要一个数组(而不是List&lt;&gt;),请说new T[length]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-15
    • 1970-01-01
    • 2021-06-04
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多