无法从“方法组”转换为“System.Action< object>”错误 [英] Cannot convert from 'method group' to 'System.Action<object>' error

查看:4415
本文介绍了无法从“方法组”转换为“System.Action< object>”错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下函数:

public void DelegatedCall(Action<Object> delegatedMethod)

并定义了以下方法

public void foo1(String str) { }

但是,当我尝试调用 DelegateCall foo1

However, when I try to call DelegateCall with foo1:

DelegatedCall(foo1);

...我得到以下编译器错误:

...I get the following compiler error:


参数1:无法从方法组转换为System.Action< object>

这个错误的原因是什么,如何纠正?不幸的是,将 foo1 转换为 Action 不是一个选项。

What is the reason for this error and how can I correct it? Unfortunately, casting foo1 to Action is not an option.

推荐答案

DelegatedCall 期望一个代理服用任何对象作为参数。但是您传递给 DelegatedCall 的函数 foo1 只能处理 string 参数。所以转换不是类型安全的,因此是不可能的。

DelegatedCall expects a delegate that takes any object as an argument. But your function foo1 that you are passing to DelegatedCall can only cope with a string argument. So, the conversion isn't type-safe and thus is not possible.

输入参数是 contra-variant ,但您的代码需要 协方差 。 (请参阅协方差和对角差异之间的差异。)

您可以使 DelegatedCall 通用:

DelegatedCall<T>(Action<T> action)

委托:

DelegatedCall(Delegate action)

但是实现它是丑陋的,需要反思。它也不会验证函数在编译时只有一个参数。

But then implementing it is ugly and requires reflection. It also doesn't verify that the function has only one parameter at compile-time.

这篇关于无法从“方法组”转换为“System.Action&lt; object&gt;”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆