本文介绍了不包括在通用约束类型(可能吗?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时可以从一组可能的类型,可在一个通用的参数被用于排除特定类型的?如果是这样如何。

Is possible to exclude specific types from the set of possible types, that can be used in a generic parameter? If so how.

例如

Foo<T>() : where T != bool

意味着任何类型除了布尔类型

would mean any type except for the type bool.

修改

为什么呢?

下面code是我尝试执行负约束。

The following code is my attempt to enforce the negative constraint.

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邪恶code的信念是正确的,而位。

As you can see it involves a bit of faith in the overload resolution being correct, and bit of @jonskeet -esque evil code.

注释掉部分与推断的类型例如交易,这是行不通的。

Comment out the section with deals with the inferred type example and it doesn't work.

这将是好多了具有排除通用约束。

It would be so much better to have the excluded generic constraint.

推荐答案

不,你不能一次性排除这样的使用类型约束。你可以在运行时做,但:

Nope, you can't make one-off exclusions like that using type constraints. You can do it at runtime though:

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

这篇关于不包括在通用约束类型(可能吗?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:54