无法从“方法组”转换;到“System.Action<对象>”错误对象>
我创建了以下函数:
public void DelegatedCall(Action<Object> delegatedMethod)
并定义了以下方法
public void foo1(String str) { }
但是,当我尝试使用 foo1
调用 DelegateCall
时:
DelegatedCall(foo1);
...我收到以下编译器错误:
参数 1:无法从“方法组”转换为“System.Action
此错误的原因是什么以及如何更正它?不幸的是,不能将 foo1
转换为 Action
。
I have created the following function:
public void DelegatedCall(Action<Object> delegatedMethod)
And defined the following method
public void foo1(String str) { }
However, when I try to call DelegateCall
with foo1
:
DelegatedCall(foo1);
...I get the following compiler error:
Argument 1: cannot convert from 'method group' to 'System.Action<object>'
What is the reason for this error and how can I correct it? Unfortunately, casting foo1
to Action
is not an option.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
DeleatedCall
需要一个接受任何对象
作为参数的委托。但是您传递给DelegateCall
的函数foo1
只能处理string
参数。因此,转换不是类型安全的,因此是不可能的。输入参数是逆变,但您的代码需要协方差。 (请参阅协方差与反方差之间的差异。)
您可以使
DeleatedCall 通用:
...或者让它接受任何委托:
但是实现它很丑陋并且需要反射。它还不会在编译时验证该函数是否只有一个参数。
DelegatedCall
expects a delegate that takes anyobject
as an argument. But your functionfoo1
that you are passing toDelegatedCall
can only cope with astring
argument. So, the conversion isn't type-safe and thus is not possible.Input parameters are contra-variant, but your code needs covariance. (See Difference between Covariance & Contra-variance.)
You can make
DelegatedCall
generic:...or have it take any delegate:
But then implementing it is ugly and requires reflection. It also doesn't verify that the function has only one parameter at compile-time.
方差并非如此。 即使在 4.0 中,它也不会
相信每个对象都是字符串。
请注意,如果它是
foo1(object)
和Action
(即相反),它可能会起作用(在 4.0 中),因为每个字符串 是一个对象。Variance doesn't work that way around; you would need
As even in 4.0 it won't believe that every object is a string.
Note that if it was
foo1(object)
andAction<string>
(i.e. the other way around) it probably would work (in 4.0), since every string is an object.