是一部分有可能做到這一點,你需要創建類似於C++的enable_if
public class ClassTag<V> where V : class { }
public class StructTag<V> where V : struct { }
public void Func<V>(V v, ClassTag<V> dummy = null) where V : class
{
Console.Writeln("class");
}
public void Func<V>(V v, StructTag<V> dummy = null) where V : struct
{
Console.Writeln("struct");
}
public void Func<V>(V? v, StructTag<V> dummy = null) where V : struct
{
Console.Writeln("struct?");
}
static void Main()
{
Func("A");
Func(5);
Func((int?)5);
}
它可以擴展爲使用任何不相交的where
來區分過載。 唯一的缺點是它不能在另一個內部通用的方法來使用:
public static void Z1<T>(T t) // where T : class
{
Func(t); //error there
}
public static void Z2<T>(T t) where T : class
{
Func(t); //ok
}
編輯 但在這種情況下,使用dynamic
的可能性來解決此限制:
public static void Z1<T>(T t)
{
Func((dynamic)t); //if `T == int` it will call "struct" version
}
唯一的缺點運行時間成本類似於調用Dictionary<,>
索引。
的可能的複製[通用的限制,其中,T:struct和其中T:類](http://stackoverflow.com/questions/2974519/generic-constraints-where-t-struct-and-where-叔類)。另見Eric Lippert的文章[here](http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx)。 –
@Frederic:我怎麼錯過那個! –
顯然,邊欄中的「相關」窗格也沒有選擇它,所以它可能比平常更復雜;) –