2012-05-15 143 views
2

“其中T从xxx派生”我想用它的参数的泛型类和力量一个来自一些基类派生。 喜欢的东西:泛型:如何实现:

public class BaseClass { } 
public class DerivedClass : BaseClass { }   
public class Manager<T> where T : derivesfrom(BaseClass) 

我现在做它的方式是在运行时在构造函数中:

public class Manager<T> where T : class 
{ 
    public Manager() 
    { 
     if (!typeof(T).IsSubclassOf(typeof(BaseClass))) 
     { 
      throw new Exception("Manager: Should not be here: The generic type should derive from BaseClass"); 
     } 
    } 
} 

有没有办法在编译时做到这一点? 谢谢。

+0

http://stackoverflow.com/questions/230736/can-c-sharp-generics-have-a-specific-base-type – Rawling

回答

12

你几乎拥有了:

public class Manager<T> where T : BaseClass 

阅读所有关于泛型约束here

+0

太谢谢你了。正是我需要的。 –