c#方法类型推断问题[重复]

问题描述 投票:2回答:1

我无法让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?我猜它应该,我错过了什么?

c# .net types inference
1个回答
1
投票

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

没有。

我猜它应该,我错过了什么?

你的猜测是合理的,而且很常见但不正确。

类型参数永远不会从约束推断出来,只能从参数推断出来。您有足够的信息来推断T1的类型,但编译器不会从约束中推断出T2必须是什么。

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

© www.soinside.com 2019 - 2024. All rights reserved.