我在规模很大的项目中有很多地方需要打开一个类型.显然我不能在.NET中做到这一点(以一种简单到足以满足我的方式),所以我必须进行相当数量的转换.此代码是试图在概念证明中隐藏其中一些内容的结果.
我有一个简单的继承模型:
public class Base { }
public class Derived : Base { public string Name { get; set; } }
Run Code Online (Sandbox Code Playgroud)
和我的班级:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
我运行它:
static void Main(string[] args)
{
var ts = new …Run Code Online (Sandbox Code Playgroud)