首页 > 解决方案 > c# method type inference troubles

问题描述

I'm having trouble getting c# method type inference to work for me, I in essence have the following sample, but this produces the error.

CS0411 The type arguments for method 'Test.Connect(T1)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

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
{
}

Should the compiler be able to infer the parameters T1 and T2 from the class given? I would guess it should, am I missing something?

标签: c#.nettypesinference

解决方案


Should the compiler be able to infer the parameters T1 and T2 from the class given?

No.

I would guess it should, am I missing something?

Your guess is plausible, and common, but incorrect.

Type parameters are never inferred from constraints, only from arguments. You have enough information to deduce the type of T1, but the compiler does not deduce from the constraint what T2 must be.

The compiler could in theory make deductions from constraints, but we decided to infer only from arguments. The type inference algorithm is complex and hard to explain, and hard to implement; adding constraint inferences would make it more complex and harder to explain and harder to implement.


推荐阅读