希望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
的数组不是 IEnumerable
的 KeyValuePair
(单个 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/