我想要一些解释。我有一个通用类,它获取类型 T 的列表并在其上执行一个 Delegate 方法,但我想将一个 IEnumerable 传递给我的类以便能够处理列表、字典等。
假设这段代码:
public static class GenericClass<T>
{
public delegate void ProcessDelegate(ref IEnumerable<T> p_entitiesList);
public static void ExecuteProcess(ref IEnumerable<T> p_entitiesList, ProcessDelegate p_delegate)
{
p_delegate(ref p_entitiesList);
}
}
public static void Main()
{
GenericClass<KeyValuePair<string, string>.ProcessDelegate delegateProcess =
new GenericClass<KeyValuePair<string, string>.ProcessDelegate(
delegate (ref IEnumerable<KeyValuePair<string, string>> p_entitiesList)
{
//Treatment...
});
Dictionary<string, string> dic = new Dictionary<string, string>;
GenericClass<KeyValuePair<string, string>>.ExecuteProcess(ref dic, delegateProcess);
//I get this error :
// cannot convert from ref Dictionary<string, string> to ref IEnumerable<KeyValuePair<string, string>>
}
我想解释一下为什么我不能将字典作为 KeyValuePair 的 IEnumerable 传递,因为 Dictionary 继承自 IEnumerable 并使用 KeyValuePair。
另外,他们这样做是更好的方法吗?