为什么不能从作为委托方法的一部分的相同泛型定义的参数中推断出泛型?

问题描述 投票:1回答:3

我不明白为什么无法推断出对GenericMethod<T>()的调用。我的实际问题包含更多通用参数,从而使调用代码非常冗长且难以阅读。

如果参数本身为'T',则

GenericMethod<T>()可以在没有显式类型参数的情况下被调用,但是约束不适用于委托,并且一旦您输入了受约束的类型参数,就回到第一个平方。

delegate void GenericDelegate<T>(T t);

static void GenericMethod<T>(GenericDelegate<T> _) { }

static void IntMethod(int _) { }

static void CallingMethod()
{
    // The type arguments for method 'GenericMethod<T>(GenericDelegate<T>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
    GenericMethod(IntMethod);
}

还有另一种方法可以使调用代码变得像这里描述的那样简单吗? GenericMethod<T>()是内部库的一部分。

c# generics delegates type-inference
3个回答
6
投票

我不明白为什么不能推断出对GenericMethod<T>()的调用。


1
投票
归结为任何语言功能的原因>

实现起来可能很昂贵(时间,资源)。


0
投票
delegate void GenericDelegate<T>(T t); static void GenericMethod<T>(GenericDelegate<T> method) { } static void Method(int _) { } static void Method(float _) { } static void CallingMethod() { GenericMethod(Method); }

[方法组Method具有两个重载时,编译器无法推断T的类型。即使该方法组仅包含一个重载,问题实际上也完全相同!

© www.soinside.com 2019 - 2024. All rights reserved.