RPD*_*ies 1 c# generics ienumerable delegates dictionary
我想要一些解释.我有一个泛型类获取类型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>>
}
Run Code Online (Sandbox Code Playgroud)
我想要一些解释,为什么我不能将Dictionnary作为KeyValuePair的IEnumerable传递,因为Dictionary继承自IEnumerable并使用KeyValuePair.
此外,他们是更好的方式吗?
因为它是一个ref参数.
甲ref参数意味着,该方法可以将新值分配给由所述呼叫者传递的字段/变量.
如果您的代码合法,该方法将能够分配一个List<KeyValuePair<string, string>>,这显然是错误的.
你不应该使用ref参数.
| 归档时间: |
|
| 查看次数: |
630 次 |
| 最近记录: |