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

时间:2012-05-17 20:06:42

标签: c# .net generics constraints

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

例如

Foo<T>() : 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<T> Lift<T>(bool value) { throw new NotSupportedException(); }
      static public Lifted<T> Lift<T>(T value) { return new Lifted<T>(value); }
    }

    public class Lifted<T>
    {
      internal readonly T _Value;
      public T Value { get { return this._Value; } }
      public Lifted(T Value) { _Value = Value; }
    }
  }
}

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

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

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

1 个答案:

答案 0 :(得分:6)

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

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