2012-05-17 56 views
8

是否可以從一組可能的類型中排除特定類型,這些類型可用於通用參數?如果是這樣的話。排除通用約束中的類型(可能嗎?)

例如

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邪惡的代碼位。

註釋掉與推斷的類型示例交易的部分,它不起作用。

擁有排除的通用約束條件會好得多。

+2

會有什麼用? 'T:x'表示'T'具有'x'的能力。消極的約束似乎毫無意義。 –

+0

你爲什麼要這麼做?你想達到什麼目的? – zmbq

+0

請參閱原始帖子上的更新編輯。 –

回答

4

不,你不能像使用類型限制那樣做一次性排除。你可以在運行時做到這一點:

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

我不是在運行時檢查泛型類型的粉絲,當編譯器可能在編譯時強制執行它時。 –

+0

@AdamSpeight你目前所要求的是不可能的。類型應該限制在他們能夠*的範圍內,而不是他們不能做的。 – vcsjones

+0

這是CLR限制嗎? –

0

這聽起來像是程序的一個方面。 也許你可以考慮面向方面編程在編譯時提供這個約束。

PostSharp應該提供這種能力。