无法从“方法组”转换为“System.Action< object>”错误

编程入门 行业动态 更新时间:2024-10-11 07:25:34
本文介绍了无法从“方法组”转换为“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;”错误

本文发布于:2023-11-12 12:58:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581560.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   错误   方法   System   gt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!