gpt4 book ai didi

c# - 动态操作 : Invalid Arguments when executed

转载 作者:行者123 更新时间:2023-12-02 19:28:29 25 4
gpt4 key购买 nike

我的项目中有很多地方需要切换类型。显然我无法在 .NET 中做到这一点(以一种足够简单以满足我的方式),所以我必须进行大量的转换。该代码是试图在概念证明中隐藏其中一些代码的结果。

我有一个简单的继承建模:

public class Base { }
public class Derived : Base { public string Name { get; set; } }

还有我的类(class):

public sealed class TypeSwitch<T> 
{
private Dictionary<Type, dynamic> _dict;

public TypeSwitch()
{
_dict = new Dictionary<Type, dynamic>();
}

public TypeSwitch<T> Add<K>(Action<K> action) where K : T
{
_dict.Add(typeof(K), action);
return this;
}

public void Execute(T item)
{
var type = item.GetType();
var action = _dict[type];

action(item);
}
}

我运行它:

static void Main(string[] args)
{
var ts = new TypeSwitch<Base>();
ts.Add<Derived>(d => { Console.WriteLine(d.Name); });

Base b = new Derived { Name = "Jonesopolis" };
ts.Execute(b);
}

当我到达action(item)时,我收到一个RuntimeBinderException

Additional information: Delegate 'System.Action<ConsoleApp.Derived>' has some invalid arguments

如果我能让它工作的话,这将是非常灵活和有帮助的。有人可以向我解释我缺少什么吗?可以让它工作吗?

最佳答案

您的item参数不是dynamic 。因为它的静态类型为 T ,输入 T (恰好是 Base )将用于重载解析。 Action<Derived>不能用 Base 调用论证。

使用dynamic在这里,您需要制作 item dynamic太:改变action(item);action((dynamic) item); .

关于c# - 动态操作<T> : Invalid Arguments when executed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32512153/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com