排除通用约束中的类型(可能?)

是否可以从可能类型的集合中排除特定类型,可以在通用参数中使用? 如果是这样的话。

例如

Foo() : where T != bool 

将意味着除bool类型之外的任何类型。

编辑

为什么?

以下代码是我尝试强制执行否定约束。

 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { var x1=Lifted.Lift("A"); var x2=Lifted.Lift(true); } static class Lifted { // This one is to "exclude" the inferred type variant of the parameter [Obsolete("The type bool can not be Lifted", true)] static public object Lift(bool value) { throw new NotSupportedException(); } // This one is to "exclude" the variant where the Generic type is specified. [Obsolete("The type bool can not be Lifted", true)] static public Lifted Lift(bool value) { throw new NotSupportedException(); } static public Lifted Lift(T value) { return new Lifted(value); } } public class Lifted { internal readonly T _Value; public T Value { get { return this._Value; } } public Lifted(T Value) { _Value = Value; } } } } 

正如你所看到的,它涉及对重载分辨率正确的一点信心,以及@jonskeet -esque恶魔代码的一点点。

注释该部分与推断类型示例的交易,它不起作用。

拥有排除的通用约束会好得多。

不,你不能像使用类型约束那样进行一次性排除。 您可以在运行时执行此操作:

 public void Foo() { if (typeof(T) == typeof(bool)) { //throw exception or handle appropriately. } }