C# 重载具有不同参数约束的泛型函数
我有以下功能:
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 )
首先...是否可以以这种方式重载功能?
如果不可能重载,我可以更具体地说明我的函数和实现吗:
public static string Foo<K, string>( this Dictionary<K, string> store, K key )
作为一点历史,我有一个带有字符串值的字典,并且我会使用字典的一致的“Foo”扩展,以允许我添加 new()对象或空字符串(视情况而定)。
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... is 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).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不,您不能通过类型参数约束进行重载。但是,是的,您可以按类型参数的数量进行重载:(
请注意,
string
不在 Foo 的泛型类型参数列表中;它本身不是类型参数,它只是用作Dictionary
的类型参数。)No, you can't overload by type parameter constraints. But yes, you can overload by the number of type parameters:
(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 forDictionary
.)