如何使字典扩展方法? [英] How to make dictionary extension-methods?
问题描述
我正在尝试编写一个独立于Key / Value的数据类型的字典
扩展。我尝试通过使用对象
数据类型传递它,假设它将适用于任何类型。
I'm trying to write a Dictionary
extension that works independently of the data types of Key/Value. I tried pass it by using the object
data type, assuming that it will works with any type.
我的代码:
public static class DictionaryExtensionsClass
{
public static void AddFormat(this Dictionary< ?? unknow type/*object*/, ??unknow type/*object*/> Dic, ??unknow type/*object*/ Key, string str, params object[] arglist)
{
Dic.Add(Key, String.Format(str, arglist));
}
}
推荐答案
你只需使方法通用:
public static void AddFormat<TKey>(this Dictionary<TKey, string> dictionary,
TKey key,
string formatString,
params object[] argList)
{
dictionary.Add(key, string.Format(formatString, argList));
}
请注意,这只是通用的键类型因为 将 code> string implements,我猜)给定你要添加一个字符串值。
Note that it's only generic in the key type as the value would have to be string
(or potentially object
or an interface that string
implements, I guess) given that you're going to add a string value to it.
不幸的是你可以'真的表达了限制,只允许值类型,其中 string
是一个有效的值在通用类型约束。
Unfortunately you can't really express the constraint of "only allow value types where string
is a valid value" in a generic type constraint.
这篇关于如何使字典扩展方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!