我有一个如下所示的类:
public class DropDownControl<T, Key, Value> : BaseControl
where Key: IComparable
{
private IEnumerable<T> mEnumerator;
private Func<T, Key> mGetKey;
private Func<T, Value> mGetValue;
private Func<Key, bool> mIsKeyInCollection;
public DropDownControl(string name, IEnumerable<T> enumerator, Func<T, Key> getKey, Func<T, Value> getValue, Func<Key, bool> isKeyInCollection)
: base(name)
{
mEnumerator = enumerator;
mGetKey = getKey;
mGetValue = getValue;
mIsKeyInCollection = isKeyInCollection;
}
我想为字典添加一个方便的函数(因为字典自身支持所有操作的高效性)。
但问题在于这样的构造函数只会指定Key和Value,而不是直接指定T,而T只是KeyValuePair。是否有一种方法告诉编译器这个构造函数的T是KeyValuePair,例如:
public DropDownControl<KeyValuePair<Key, Value>>(string name, IDictionary<Key, Value> dict) { ... }
目前我使用静态Create函数作为解决方法,但我更喜欢直接使用构造函数。
public static DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue> Create<DKey, DValue>(string name, IDictionary<DKey, DValue> dictionary)
where DKey: IComparable
{
return new DropDownControl<KeyValuePair<DKey, DValue>, DKey, DValue>(name, dictionary, kvp => kvp.Key, kvp => kvp.Value, key => dictionary.ContainsKey(key));
}