【发布时间】:2019-04-27 22:42:04
【问题描述】:
我无法让 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 吗?我猜应该是,我错过了什么吗?
【问题讨论】:
-
只有当我实际尝试在方法中使用新关键字时,新约束才有意义,新约束仅意味着指定的类型必须具有默认构造函数,但感谢您的评论
-
new Test
().Connect (new Test2()); -
我试图让编译器找出 Connect
部分,就像使用 void Connect (T value) where T : class 这样的方法定义时{ } 有了这样的定义,您可以使用这样的方法调用 Connect(new Test()) 省略类型定义,因为编译器可以弄清楚 -
但是 Connect 签名的参数类型比泛型类型参数少 (2)