我发现我经常编写这样的代码:
public void some_callback(object sender, SomeArgs args)
{
if (sender is ObjectA)
{
var objA = sender as ObjectA;
//do something
}
else if (sender is ObjectB)
{
var objB = sender as ObjectB;
//do something else
}
}
或类似地:
public void some_callback(object sender, SomeArgs args)
{
var objA = sender as ObjectA;
if (objA != null)
{
//do something
}
var objB = sender as ObjectB;
if (objB != null)
{
//do something else
}
}
我想知道的是,在C#中是否有一种快捷方式来处理这个问题?有点像:
public void some_callback(object sender, SomeArgs args)
{
with (var obj = sender as ObjectA)
{
//do something
}
else with (var obj = sender as ObjectB)
{
//do something else
}
}
答案 0 :(得分:5)
答案 1 :(得分:2)
我们在代码中也需要这个,所以使用the help of SO我创建了一个TypeSwitch
对象:
public sealed class TypeSwitch<T>
{
private readonly Dictionary<Type, Action<T>> _dict;
public TypeSwitch()
{
_dict = new Dictionary<Type, Action<T>>();
}
public TypeSwitch<T> Add<TChild>(Action<TChild> action) where TChild : T
{
_dict.Add(typeof (TChild), o => action((TChild) o));
return this;
}
public void Execute(T item)
{
var type = item.GetType();
foreach (var kvp in _dict)
{
if (type == kvp.Key || kvp.Key.IsAssignableFrom(type))
{
kvp.Value(item);
return;
}
}
throw new KeyNotFoundException($"{type} or its baseclass not located in typeswitch.");
}
}
你可以使用:
var obj = new BaseClass();
new TypeSwitch<BaseClass>()
.Add<Derived1>(d1 => { /*strongly typed d1 action */ })
.Add<Derived2>(d2 => { /*strongly typed d2 action */ })
.Execute(obj);
这对我们来说非常方便。值得注意的是,它没有像任何异步操作那样设置,但可以很容易地修改。