gpt4 book ai didi

c# - 将 Action 转换为 Action
转载 作者:行者123 更新时间:2023-11-30 14:03:28 25 4
gpt4 key购买 nike

我需要转换 Action<string>Action<object> .虽然这通常是类型不安全的,但在我的例子中,它将始终使用字符串调用。我收到此错误:

Unable to cast object of type 'System.Action<code>1[System.String]' to type 'System.Action</code>1[System.Object]'.

有什么线索吗?反射(reflection)是公平的游戏。将一个委托(delegate)包装到另一个不是

更新:我在 Creating an performant open delegate for an property setter or getter 创建了一个新问题对我的问题有更好的解释,以及我想改进的使用包装的解决方案

最佳答案

首先,它不安全。可以接受任何字符串的东西不能(必然)接受任何对象。想想一个示例方法:

void method(String s)
{
s.Trim();
}

显然,如果 s 是一个没有 Trim 的对象,这将失败.

从技术上讲,这意味着 Action在 T 上是逆变的。你可以分配一个 Action<string>到假设的 Action<SubclassString>引用,但string不能子类化。

的确,C# 允许常规的不安全转换(例如 object 本身到 string ),冒着 InvalidCastException 的风险.但是,他们选择不为不安全的委托(delegate)转换实现基础结构。

编辑:我不知道没有包装器的方法。

关于c# - 将 Action<string> 转换为 Action<object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4084273/

25 4 0