是否可以從一組可能的類型中排除特定類型,這些類型可用於通用參數?如果是這樣的話。排除通用約束中的類型(可能嗎?)
例如
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邪惡的代碼位。
註釋掉與推斷的類型示例交易的部分,它不起作用。
擁有排除的通用約束條件會好得多。
會有什麼用? 'T:x'表示'T'具有'x'的能力。消極的約束似乎毫無意義。 –
你爲什麼要這麼做?你想達到什麼目的? – zmbq
請參閱原始帖子上的更新編輯。 –