C#方法类型推断麻烦

时间:2019-04-27 22:42:05

标签: c# .net types inference

我在获取c#方法类型推断对我来说很困难,我本质上有以下示例,但这会产生错误。

CS0411无法从用法中推断出方法'Test.Connect(T1)'的类型参数。尝试显式指定类型参数。

public void Main()
{
    new Test<int>().Connect(new Test2()); // CS0411 The type arguments for method 'Test<int>.Connect<T1, T2>(T1)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
}

public class Test2 : ITest<Test<int>, Delegate>
{

}

public class Test<T>
{
    public void Connect<T1, T2>(T1 entity)
        where T1 : ITest<Test<int>, T2>
        where T2 : Delegate
    {
    }
}

public interface ITest<T1, T2>
    where T1 : Test<int>
    where T2 : Delegate
{
}

编译器是否应该能够从给定的类推断参数T1和T2?我想应该,我想念什么吗?

1 个答案:

答案 0 :(得分:1)

  

编译器是否应该能够从给定的类中推断出参数T1和T2?

否。

  

我想应该,我错过了什么吗?

您的猜测是合理且普遍的,但不正确。

类型参数从不从约束中推断,仅从参数中推断。您有足够的信息来推断T1的类型,但是编译器无法从约束条件中推断出T2必须是什么。

理论上,编译器可以从约束条件中得出推论,但我们决定仅从参数中进行推断。类型推断算法复杂,难以解释,难以实现。添加约束推断将使其变得更复杂,更难以解释且更难以实现。

相关问题