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恶魔代码.
注释该部分与推断类型示例的交易,它不起作用.
拥有排除的通用约束会好得多.
不,你不能像使用类型约束那样进行一次性排除.您可以在运行时执行此操作:
public void Foo<T>()
{
if (typeof(T) == typeof(bool))
{
//throw exception or handle appropriately.
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2842 次 |
最近记录: |