代码之家  ›  专栏  ›  技术社区  ›  Wei Lin

重载IEnumerable键/值类型和非键/值

c#
  •  1
  • Wei Lin  · 技术社区  · 6 年前

    我希望键/值类型调用 Execute<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> enums) ,非键/值类型调用 Execute<T>(this IEnumerable<T> enums)

    但Dictionary对象将调用 执行<t>(此IEnumerable<t>枚举) 而不是 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){}
    }
    
    2 回复  |  直到 6 年前
        1
  •  3
  •   mjwills Myles McDonnell    6 年前

    一个数组 Dictionary IEnumerable 属于 KeyValuePair (单个) 词典 是-但那不是你有的。

    我怀疑你的意思是:

    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 .

        2
  •  2
  •   Matthew Watson    6 年前

    试试这个:

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

    注意使用 SelectMany() AsEnumerable() .