c#模板如何将约束应用于派生自某些东西的类

本文关键字:派生 应用于 约束 | 更新日期: 2023-09-27 18:06:19

又是愚蠢的问题。

我有这个类,通过基类拉入一些代码,像这样:

class TVIRoot : OURTreeNodeImpl { }

我现在想添加一些模板功能

class TVIRoot<TLabelHandler> : OURTreeNodeImpl { }

但是当我需要提供一些约束时,我不知道我需要什么样的手指变形来编译它。

class TVIRoot<TLabelHandler> where TLabelHandler : new(), OURTreeNodeImpl { } //no    
class TVIRoot<TLabelHandler> where TLabelHandler : SomeClass : OURTreeNodeImpl { } //no
class TVIRoot<TLabelHandler> : OURTreeNodeImpl, where TLabelHandler : SomeClass { } //no

这能做到吗?

许多谢谢。

bg

c#模板如何将约束应用于派生自某些东西的类

class TVIRoot<TLabelHandler> : OURTreeNodeImpl where TLabelHandler : SomeClass { } //yes

约束出现在基类继承之后,下面是一个例子:

public interface  IFood
{
}
public class Animal
{
}
public class Cat<T> : Animal where T : IFood
{
    public void Eat(T food)
    {
    }
}

查看更多详细信息:http://msdn.microsoft.com/en-US/library/d5x73970 (v = vs.80) . aspx