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

标签 c# generics dynamic types

我的项目中有很多地方需要切换类型。显然我无法在 .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/

相关文章:

vba - 如何通过 CallByName 传递参数数组 ByRef?

c# - 在 linq 查询中使用 C# 扩展方法作为谓词

c# - 在不修改注册表项的情况下读取 Excel InterMixed DataType

dynamic - Lisp 动态作用域 : A powerful short example reasoning it?

java - 如何在类中引用嵌套模板参数的嵌套类型?

generics - 如何在线程之间共享包含幻像指针的结构?

Android 在此图片之上绘制图片(动态)

c# - 删除的文件还存在吗?

c# - 具有多个 OR 条件的 EF core 连接

c++ - 各种类型的容器 - C++