开发者

c# overload generic functions with different parameter constraints

I have the following functions:

public static V AddIfNotPresent<K, V>( this Dictionary<K, V> store, K key ) where V : new()

public static V AddIfNotPresent<K, V>( this Dictionary<K, V> store, K key )

First off... 开发者_如何学Gois it possible to overload the functions in this way?

If overloading is not possible could I be more specific with my functions and implements say:

public static string Foo<K, string>( this Dictionary<K, string> store, K key )

As a little History I have a Dictionary with string values and I'd live a consistent 'Foo' extension of the Dictionary to allow me to add new() objects or an empty string (as appropriate).


No, you can't overload by type parameter constraints. But yes, you can overload by the number of type parameters:

public static string Foo<TKey>(this Dictionary<TKey, string> store, TKey key)

(Note that string isn't in the generic type parameters list for Foo; it's not a type parameter itself, it's just used as a type argument for Dictionary.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜