c# - 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?
解决方案
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.
推荐阅读
- firebase - 尝试处理 firebase 存储异常不起作用(颤振)
- javascript - Javascript 空验证在发送到数据库之前不起作用
- typescript - Typescript 会自动检测 void 函数吗?
- python - 一种用于销售预测和内核的热编码已死
- python - 访问 ndarray 的元素
- python - 通过匹配python中的正则表达式将非常大的文本拆分为文档
- android - Android Kotlin 应用 RecyclerView 无显示,适配器不工作,无错误
- perl - Perl 存储输出
- android - 没有代理的 Android Studio
- python - dijkstras 算法找不到实际的最短路径