相关疑难解决方法(0)

泛型:为什么编译器在这种情况下不能推断出类型参数?

我想写一个扩展方法,它可以在字典上工作,它的值是某种顺序.不幸的是,编译器似乎无法从我对该方法的使用中推断出泛型参数; 我需要明确指定它们.

public static void SomeMethod<TKey, TUnderlyingValue, TValue>
    (this IDictionary<TKey, TValue> dict)
    where TValue : IEnumerable<TUnderlyingValue> { }    

static void Usage()
{
    var dict = new Dictionary<int, string[]>();
    var dict2 = new Dictionary<int, IEnumerable<string>>();

    //These don't compile
    dict.SomeMethod();
    SomeMethod(dict); // doesn't have anything to do with extension-methods
    dict2.SomeMethod(); // hoped this would be easier to infer but no joy


    //These work fine
    dict.SomeMethod<int, string, string[]>();
    dict2.SomeMethod<int, string, IEnumerable<string>>();
}
Run Code Online (Sandbox Code Playgroud)

我意识到类型推断不是一门精确的科学,但我想知道是否有一些基本的"规则"我在这里缺失 - 我不熟悉规范的细节.

  1. 这是推理过程的缺点还是我期望编译器在这种情况下应该"弄明白"不合理(或许是歧义)?
  2. 我可以改变方法的签名,使其同样功能但"可推断"吗?

c# generics type-inference

8
推荐指数
1
解决办法
1511
查看次数

标签 统计

c# ×1

generics ×1

type-inference ×1