代码之家  ›  专栏  ›  技术社区  ›  kevindaub

如何创建具有继承性的泛型类?

  •  1
  • kevindaub  · 技术社区  · 15 年前

    如何使以下代码工作?我觉得我不太了解C仿制药。也许,有人能给我指明正确的方向。

        public abstract class A
        {
        }
    
        public class B : A
        {
        }
    
        public class C : A
        {
        }
    
        public static List<C> GetCList()
        {
            return new List<C>();
        }
    
        static void Main(string[] args)
        {
            List<A> listA = new List<A>();
    
            listA.Add(new B());
            listA.Add(new C());
    
            // Compiler cannot implicitly convert
            List<A> listB = new List<B>();
    
            // Compiler cannot implicitly convert
            List<A> listC = GetCList();
    
            // However, copying each element is fine
            // It has something to do with generics (I think)
            List<B> listD = new List<B>();
            foreach (B b in listD)
            {
                listB.Add(b);
            }
        }
    

    这可能是一个简单的答案。

    更新: 首先,这在C 3.0中是不可能的,但在C 4.0中是可能的。

    要让它在C 3.0中运行,在4.0之前这只是一个解决方法,请使用以下方法:

            // Compiler is happy
            List<A> listB = new List<B>().OfType<A>().ToList();
    
            // Compiler is happy
            List<A> listC = GetCList().OfType<A>().ToList();
    
    2 回复  |  直到 15 年前
        1
  •  3
  •   Matthew Whited    15 年前

    你可以一直这样做

    List<A> testme = new List<B>().OfType<A>().ToList();
    

    正如《博扬·雷斯尼克》所指出的,你也可以…

    List<A> testme = new List<B>().Cast<A>().ToList();
    

    需要注意的一点是,如果一个或多个类型不匹配,则强制转换<t>()将失败。其中,类型<t>()将返回仅包含可转换对象的IEnumerable<t>。

        2
  •  5
  •   Eric Lippert    15 年前

    这不起作用的原因是它不能确定是安全的。假设你有

    List<Giraffe> giraffes = new List<Giraffe>();
    List<Animal> animals = giraffes; // suppose this were legal.
    // animals is now a reference to a list of giraffes, 
    // but the type system doesn't know that.
    // You can put a turtle into a list of animals...
    animals.Add(new Turtle());  
    

    嘿,你刚刚把一只乌龟放到长颈鹿的列表中,现在已经违反了类型系统的完整性。这就是为什么这是非法的。

    这里的关键是“动物”和“长颈鹿”指的是同一个物体,而这个物体是长颈鹿的列表。但是长颈鹿的种类不能像动物的种类那样多,特别是不能包含海龟。