【问题标题】:Best way to cast from Animal[] to Dog[]从 Animal[] 转换为 Dog[] 的最佳方式
【发布时间】:2009-06-03 11:11:59
【问题描述】:

如果 Dog 从 Animal 继承。

我有一个 Animal[],我碰巧知道它只包含狗。得到 Dog[] 的最快/最好的方法是什么?我使用了 new ArrayList(oldarray).ToArray(typeof(Dog));到目前为止,但感觉有点笨拙,我想知道是否有更优雅的东西。

更新:使用 .net 2.0 配置文件。应该马上就提到这一点。我希望在这种情况下编辑原始问题符合 stackoverflow 网络礼节。我期待着我们可以升级和使用 Linq 的那一天。

再见,卢卡斯

【问题讨论】:

    标签: c# arrays casting


    【解决方案1】:
    var dog_arr = Array.ConvertAll(animal_arr, x => (Dog) x);
    

    【讨论】:

    • 我不得不使用 Array.ConvertAll。除此之外,我真的很喜欢这个解决方案的优雅。
    【解决方案2】:

    使用 LINQ 这将是

    oldarray.Cast<Dog>().ToArray();
    

    【讨论】:

    • 虽然这很优雅,但恕我直言,效率也很低
    • 效率是一种意见吗?我认为编译器应该能够自动修复这里提出的低效率问题。我也觉得做不到。很少有问题,幸运的是。
    【解决方案3】:

    也许您一开始就可以将它创建为 Dog[] 数组?

    给定:

    interface ICage {
        Animal[] GetAnimals();
    }
    

    如果实例化一个包含 Dogs 的 Animal[] 数组,则不能强制转换该数组:

    class DogCage : ICage {
        Animal[] GetAnimals() { return new Animal[] { spot, fido }; }
    }
    

    如果你实例化一个包含 Dogs 的 Dog[] 数组,它仍然可以作为 Animal[] 数组返回,但你也可以将数组强制转换回 Dog[]。

    class DogCage : ICage {
        Animal[] GetAnimals() { return new Dog[] { spot, fido }; }
    }
    

    现在这将起作用:

    Dog[] dogs = (Dog[])cage.GetAnimals();
    

    【讨论】:

      【解决方案4】:

      您可以使用通用集合,例如从System.Collections.Generic 列出而不是数组,然后使用以下内容:

      List<Animal> animals = new List<Animal>();
      animals.Add(new Dog());
      List<Dog> dogs = animals.ConvertAll(delegate(Animal animal) { return (Dog)animal; });
      

      如果你真的需要它在一个数组中,你也可以这样做:

      animals.ConvertAll(delegate(Animal animal) { return (Dog)animal; }).ToArray();    
      

      【讨论】:

        猜你喜欢
        • 2015-12-18
        • 2017-09-19
        • 2013-06-23
        • 1970-01-01
        • 2011-04-02
        • 1970-01-01
        • 1970-01-01
        • 2010-10-15
        • 2016-05-10
        相关资源
        最近更新 更多