【发布时间】:2015-12-07 08:19:48
【问题描述】:
在我的大型项目中有很多地方需要切换类型。显然我不能在 .NET 中做到这一点(以一种足够简单的方式让我满意),所以我必须进行大量的转换。这段代码是试图在概念验证中隐藏其中一些内容的结果。
我有一个简单的继承建模:
public class Base { }
public class Derived : Base { public string Name { get; set; } }
和我的班级:
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 说
附加信息:Delegate 'System.Action
' 有一些无效参数
如果我能让它工作,这将是非常巧妙和有用的。有人可以向我解释我错过了什么吗?是否有可能让这个工作?
【问题讨论】: