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

Ada*_*ght 11 .net c# generics constraints

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

例如

Foo<T>() : where T != bool
Run Code Online (Sandbox Code Playgroud)

将意味着除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; }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

vcs*_*nes 6

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

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

  • @AdamSpeight F# 的 `not` 不适用于任何地方,仅适用于 `struct`。你不能在 F# 中说 `not bool`。`not struct` 与 C# 的 `Foo&lt;T&gt;() where T:class` 相同。是的,这是 CLR 限制。 (3认同)
  • 我不喜欢在运行时检查泛型类型,因为编译器可能会在编译时强制执行它。 (2认同)
  • 因为在F#中你可以限制它`:not struct` (2认同)
  • 使用重载可能会更有帮助,因为抛出异常只会在运行时发生,并且在编写代码时了解此行为可能会很有用。 (2认同)