繁体   English   中英

为什么我不能通过字典 <string, string> 到IEnumerable <KeyValuePair<string, string> &gt;作为通用类型

[英]Why can't i pass Dictionary<string, string> to IEnumerable<KeyValuePair<string, string>> as generic type

我想要一些解释。 我有一个泛型类,它获取类型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>>
        }

我想解释一下为什么我不能将Dictionnary作为KeyValuePair的IEnumerable传递,因为Dictionary从IEnumerable继承并使用KeyValuePair。

另外,他们这样做的更好方法吗?

因为它是ref参数。

ref参数表示该方法可以为调用者传递的字段/变量分配一个新值。

如果您的代码合法,则该方法将能够分配List<KeyValuePair<string, string>> ,这显然是错误的。

您不应使用ref参数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM