我正在尝试将函数引用存储在委托(delegate)类型中以备后用。
这是我正在做的:
class Program
{
static void Test()
{
}
static void Main(string[] args)
{
Delegate t= (Delegate)Test;
}
}
在此我遇到以下错误:
Cannot convert method group 'Test' to non-delegate type 'System.Delegate'.
Did you intend to invoke the method?
为什么会这样?
最佳答案
您真的不应该使用 Delegate
类型来存储委托(delegate)。您应该使用特定类型的委托(delegate)。
在几乎所有情况下,您都可以使用Action
或Func
作为您的委托(delegate)类型。在这种情况下,Action
是合适的:
class Program
{
static void Test()
{
}
static void Main(string[] args)
{
Action action = Test;
action();
}
}
从技术上讲,您可以通过执行以下操作来获取 Delegate
的实例:
Delegate d = (Action)Test;
但实际使用 Delegate
与实际特定类型的委托(delegate)(例如 Action
)相反,会很困难,因为编译器将不再知道该方法的签名是,所以它不知道应该向它传递什么参数。
关于c# - 无法将方法组 '' 转换为非委托(delegate)类型 'System.Delegate'。您是否打算调用该方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15204639/