Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#方法类型推理故障_C#_.net_Types_Inference - Fatal编程技术网

c#方法类型推理故障

c#方法类型推理故障,c#,.net,types,inference,C#,.net,Types,Inference,我很难让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 in

我很难让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
{
}
public void Main()
{
new Test().Connect(new Test2());//CS0411无法从用法推断方法“Test.Connect(T1)”的类型参数。请尝试显式指定类型参数。
}
公共类Test2:ITest
{
}
公开课考试
{
公共void Connect(T1实体)
其中T1:ITest
其中T2:代表
{
}
}
公共接口测试
其中T1:测试
其中T2:代表
{
}
编译器应该能够从给定的类中推断出参数T1和T2吗?我想应该是的,我是不是遗漏了什么

编译器应该能够从给定的类中推断出参数T1和T2吗

没有

我想应该是的,我是不是遗漏了什么

你的猜测是可信的,很普通,但不正确

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


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

新约束只在我实际尝试在方法中使用新关键字时才起作用,新约束只意味着指定的类型必须具有默认构造函数,但感谢commentnew Test().Connect(new Test2());我试图让编译器找出连接部分,比如当使用void Connect(T value)这样的方法定义时,其中T:class{}有了这样的定义,就可以使用像Connect(new Test())这样的方法调用省略类型定义,因为编译器可以计算出连接签名的参数类型比泛型类型param(2)的参数类型少,所以编译器无法为我推断T2,除非逐字传递类型?@Ronald:没错。如果类型参数出现在非正式参数类型中,则类型推断无法成功。感谢您提供的见解,希望能够使基类更易于使用,但我认为重新设计实现才是可行的方法。@Ronald:通常在这种情况下,明智的做法是
公共void Connect(ITest实体)
Delegate
约束可疑。你能说出你想做什么吗?这听起来像是一个“XY”问题;对于如何解决真正的问题,你有一个错误的想法,你问的是错误的想法。问一个关于实际问题的问题。你是对的,委托只是作为示例出现在脑海中的第一个类,我在这里创建了一个示例,我的问题在第122行这里我希望能够只传递一个继承的实体类,而不传递所有类型参数