通用约束排除

很抱歉问愚蠢的问题

是否有可能以这样的方式强制执行约束,即给定的T可以从任何引用类型派生,除了一些A,B,C(其中A,B,C是引用类型)。 (即)

Where T : class except A,B,C 

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

 public class Foo { 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 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 cannot be instantiated with type {0}.", typeof(A) )); } } } 

不,您只能指定它从特定类型inheritance,是值或引用类型,还是必须具有默认构造函数。 请记住,这是为了编译器的利益,而不是开发人员。 🙂

您可能做的最好的事情是在运行时抛出exception。

对不起你可以了解如何限制在这里 ……

没有。没有类型的否定。 where子句仅允许您禁用特定类型。