泛型:如何实现:“其中 T 派生自 xxx”

本文关键字:其中 派生 xxx 何实现 实现 泛型 | 更新日期: 2023-09-27 18:34:15

我想使用一个泛型类,并强制它的一个参数从某个基类派生。像这样:

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");
        }
    }
}

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

泛型:如何实现:“其中 T 派生自 xxx”

你几乎拥有它:

public class Manager<T> where T : BaseClass

在此处阅读有关通用约束的所有信息。