c# 方法类型推断的麻烦
c# method type inference troubles
我无法让 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
{
}
编译器是否应该能够从给定的 class 中推断出参数 T1 和 T2?我猜应该是这样,我是不是漏掉了什么?
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?
您的猜测合理且常见,但不正确。
类型参数永远不会从约束中推断出来,只能从参数中推断出来。您有足够的信息来推断 T1 的类型,但编译器不会从约束中推断出 T2 必须是什么。
编译器理论上可以从约束中进行推论,但我们决定只从参数中推断。类型推断算法复杂且难以解释,难以实现;添加约束推理会使它变得更复杂,更难解释,也更难实施。
我无法让 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
{
}
编译器是否应该能够从给定的 class 中推断出参数 T1 和 T2?我猜应该是这样,我是不是漏掉了什么?
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?
您的猜测合理且常见,但不正确。
类型参数永远不会从约束中推断出来,只能从参数中推断出来。您有足够的信息来推断 T1 的类型,但编译器不会从约束中推断出 T2 必须是什么。
编译器理论上可以从约束中进行推论,但我们决定只从参数中推断。类型推断算法复杂且难以解释,难以实现;添加约束推理会使它变得更复杂,更难解释,也更难实施。