C# 重载 IEnumerable Key/Value 类型和非 Key/Value

标签 c#

希望Key/Value Type调用Execute<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> enums) ,非 Key/Value 类型调用 Execute<T>(this IEnumerable<T> enums)

但是 Dictionary 对象会调用 Execute<T>(this IEnumerable<T> enums)而不是 Execute<TKey, TValue>(this ICollection<KeyValuePair<TKey, TValue>> enums)

例如:

void Main(){
    var keyValueTypeData = new[] {
        new Dictionary<string, string> (){{"Name" , "ITWeiHan" }}
    }.AsEnumerable();
    keyValueTypeData.Execute(); //call Execute<T>

    var nonKeyValueTypeData = new[] {new {Name ="ITWeiHan" }};
    nonKeyValueTypeData.Execute(); //call Execute<T>
}

public static class Test
{
    public static void Execute<TKey, TValue>(this IEnumerable<IEnumerable<KeyValuePair<TKey, TValue>>> enums){}

    public static void Execute<T>(this IEnumerable<T> enums){}
}

最佳答案

Dictionary 的数组不是 IEnumerableKeyValuePair (单个 Dictionary 是 - 但那不是您所拥有的)。

我怀疑你的意思是:

using System.Collections.Generic;

namespace Test
{
    public static class Test
    {
        public static void Execute<TKey, TValue>(this IEnumerable<IEnumerable<KeyValuePair<TKey, TValue>>> enums)
        {

        }

        public static void Execute<T>(this IEnumerable<T> enums)
        {
        }
    }

    public class Program
    {
        public static void Main()
        {
            IEnumerable<IEnumerable<KeyValuePair<string, string>>> data = new[] {
                new Dictionary<string, string> (){
                    {"Name" , "ITWeiHan" }
                }
            };
            data.Execute();
        }
    }
}

请注意,部分解决方案是明确类型 - 以确保“鼓励”编译器选择我希望它选择的方法。

即我用 IEnumerable<IEnumerable<KeyValuePair<string, string>>>而不是 var .

关于C# 重载 IEnumerable Key/Value 类型和非 Key/Value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54250267/

相关文章:

javascript - jQuery 克隆无法与同步融合控件一起使用

c# - 嵌入语句错误

c# - CQRS 和主键 : guid or not?

c# - AjaxToolkit 日历扩展器上未捕获的 Sys.ArgumentOutOfRangeException : Sys. ArgumentOutOfRangeException : Value must be an integer.

c# - 如何从您的自定义 HTTP 模块创建一个独立的 HTTP 服务器?

c# - 多步算法的设计模式

c# - 为什么在 C# 中没有用于 8 位和 16 位整数的算术运算符 (+,-,*,/,%)?

c# - 无法通过操作设置 cookie

c# - 使用 System.Reflection 从 DLL 程序集中获取 DataMember

c# - 执行迁移后出错(.Net 后端)