我想要一些解释。我有一个泛型类,它获取类型为T的列表并在上面执行Delegate方法,但我想将IEnumerable传递给我的类,以便能够处理list、Dictionary等。
假设此代码:
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>>
}
我想解释一下为什么我不能将Dictionary作为KeyValuePair的IEnumerable传递,因为Dictionary继承自IEnumeraable并使用KeyValuePair。
此外,他们这样做更好吗?
因为它是一个ref
参数。
ref
参数表示该方法可以为调用方传递的字段/变量分配一个新值。
如果您的代码是合法的,那么该方法将能够分配一个List<KeyValuePair<string, string>>
,这显然是错误的。
不应使用ref
参数。