通用约束排除

use*_*546 4 c# generics

很抱歉问愚蠢的问题

是否有可能对泛型强制执行约束,使得给定的T可以从任何引用类型派生,除了一些A,B,C(其中A,B,C是引用类型).(即)

Where T : class except A,B,C
Run Code Online (Sandbox Code Playgroud)

dtb*_*dtb 5

不.但您可以在运行时检查这些类:

public class Foo<T>
{
    static Foo()
    {
        // one of the following depending on what you're trying to do
        if (typeof(A).IsAssignableFrom(typeof(T)))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with {0} because it derives from or implements {1}.",
                typeof(T),
                typeof(A)
                ));
        }

        if (typeof(T) == typeof(A))
        {
            throw new NotSupportedException(string.Format(
                "Generic type Foo<T> cannot be instantiated with type {0}.",
                typeof(A)
                ));
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 如果将检查移动到静态构造函数,它只会运行一次,而不是每次创建类的新实例时.但是,由于调试问题,在这种情况下包含一个带有"NotSupportedException"的正确错误消息非常重要.我编辑了帖子以使用该方法. (2认同)