简体   繁体   English

泛型类型中的C#多态

[英]C# polymorphism in Generic types

class Base
{}

class Sub : Base
{}


void AddNewBase(Base t, LinkedList<Base> list){ ... }
...
{

    Sub asub = new Sub();

    LinkedList<Sub> asubList = new LinkedList<Sub>();
    AddNewBase(asub,asubList) // doesn't work
}

basically, I have a custom insert function that takes a new item and a list to put it in, and it does some 'sorting' stuff to find a good place to put it in the list. 基本上,我有一个自定义插入函数,它接受一个新项目和一个列表来放入它,它做了一些“排序”的东西,找到一个好的地方把它放在列表中。

problem is, I want to do this based on properties in 'Base' so it would be good to have just one function that could do this for all lists of sub types. 问题是,我想基于'Base'中的属性来做这个,所以最好只有一个函数可以为所有子类型列表执行此操作。

I think what I kind of want is: 我想我想要的是:

static void AddNewBase<T>(T t, LinkedList<T> list){ ... }

but with some way of clarifying T like: 'where T is a sub class of Base' 但有一些澄清T的方式:'其中T是Base的子类'

您可以在类型参数上声明约束

static void AddNewBase<T>(T t, LinkedList<T> list) where T : Base { ... }

You can use where keyword in the same way and you do not need a generic type. 您可以以相同的方式使用where关键字,而不需要泛型类型。

Here is the IComparable implementation which probably is what you could be looking for in a classic sorting problem: 以下是IComparable实现,它可能是您在经典排序问题中可能正在寻找的内容:

    static void AddNewBase<T>(T t, LinkedList<T> list) where T : IComparable
    {
        //
    }

In C# 4, you can use covariance to make this work. 在C#4中,您可以使用协方差来完成这项工作。 You have to select from one of the covariant generic collection interfaces though. 您必须从其中一个协变通用集合接口中进行选择。 For example, redeclaring your method as: 例如,将您的方法重新声明为:

static void AddNewBase(Base t, IEnumerable<Base> list) { //... }

Would allow you to call AddNewBase with a LinkedList<Sub> . 允许您使用LinkedList<Sub>调用AddNewBase

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

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