问题描述
我一直在玩一些泛型和委托,但我发现了一些我不理解的东西.我有非常相似的通用静态方法,一个接受 Action<T>
,第二个接受 Func<T>
.现在的问题是:如果我调用没有显式类型的接受 Func<T>
的那个,编译器就可以了.但是接受 Action<T>
我的程序无法编译(请参阅错误消息的代码).
I've been playing a little with generics and delegates and I have found something I don't understand. I have quite similar generic static methods, one accepts Action<T>
and the second one accepts Func<T>
. Now the problem: if I call the one accepting Func<T>
without explicit Type, compiler is fine with that. But with the one accepting Action<T>
my program can't be compiled (see the code for error message).
我的问题是:为什么编译器能够识别返回类型,但不能识别参数类型?
My question is: Why is compiler able to recognize return type, but is not able to recognize argument type?
public interface IMessage
{ }
public class Message : IMessage
{
}
static void HandleAction<TMessage>(Action<TMessage> action)
where TMessage : IMessage
{ }
static void HandleFunction<TMessage>(Func<TMessage> action)
where TMessage : IMessage
{ }
static void A(Message message)
{ }
static Message F()
{
return new Message();
}
static void Main(string[] args)
{
// this one is ok
HandleFunction(F);
// compiler error:
// The type arguments for method
// 'template_test.Program.HandleAction<TMessage>(System.Action<TMessage>)'
// cannot be inferred from the usage.
//Try specifying the type arguments explicitly.
//HandleAction(A);
// this one is ok
HandleAction<Message>(A);
}
我在 Visual Studio 2012 中使用 .NET 4.5.
I'm using .NET 4.5 in Visual Studio 2012.
推荐答案
方法可以通过其参数重载,所有重载形成一个方法组,例如 void Xyz(int i)
和 void Xyz(string s)
位于名为 Xyz
的同一方法组中.即使用户只定义了一个方法,编译器也无法推断出一种类型的参数,因为编译器的行为非常严格.
Methods can be overloaded by their arguments and all overloads form one method group, so for example void Xyz(int i)
and void Xyz(string s)
are within same method group called Xyz
. Compiler is not able to deduct a type of argument even if user defines only one method, because behaviour of compiler is quite strict.
方法不能被返回类型重载,所以你不能在同一个类中有 int Xyz()
和 string Xyz()
.返回类型很容易被编译器推断出来,因为没有重载.
Methods can't be overloaded by return types, so you can't have int Xyz()
and string Xyz()
within same class. Return type can be deducted by compiler easily, because there is no overloading.
第一次对我来说不是很明显,但是当我意识到我可以创建一个重载之后就很清楚了.
It was not obvious for me for the first time, but it has been quite clear after I realized that I could create an overload.
这篇关于类型参数来自 Action<T>不能推断,而是从 Func<T>可的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!