无法从“方法组”转换;到“System.Action<对象>”错误

发布于 2024-10-12 03:12:53 字数 504 浏览 2 评论 0原文

我创建了以下函数:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小嗷兮 2024-10-19 03:12:53

DeleatedCall 需要一个接受任何对象 作为参数的委托。但是您传递给 DelegateCall 的函数 foo1 只能处理 string 参数。因此,转换不是类型安全的,因此是不可能的。

输入参数是逆变,但您的代码需要协方差。 (请参阅协方差与反方差之间的差异。)

您可以使DeleatedCall 通用:

DelegatedCall<T>(Action<T> action)

...或者让它接受任何委托:

DelegatedCall(Delegate action)

但是实现它很丑陋并且需要反射。它还不会在编译时验证该函数是否只有一个参数。

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.

Input parameters are contra-variant, but your code needs covariance. (See Difference between Covariance & Contra-variance.)

You can make DelegatedCall generic:

DelegatedCall<T>(Action<T> action)

...or have it take any delegate:

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.

小巷里的女流氓 2024-10-19 03:12:53

方差并非如此。 即使在 4.0 中,它也不会

DelegatedCall(obj => foo1((string)obj));

相信每个对象都是字符串。

请注意,如果它是 foo1(object)Action (即相反),它可能会起作用(在 4.0 中),因为每个字符串 是一个对象。

Variance doesn't work that way around; you would need

DelegatedCall(obj => foo1((string)obj));

As even in 4.0 it won't believe that every object is a string.

Note that if it was foo1(object) and Action<string> (i.e. the other way around) it probably would work (in 4.0), since every string is an object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文