使用映射而不是switch / if else调用具有不同参数的方法 [英] Calling methods with different parameters using a map instead of switch/if else

查看:84
本文介绍了使用映射而不是switch / if else调用具有不同参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一种c#方法,该方法根据某些条件调用不同的方法,我想知道是否可以在不使用switch或其他语句的情况下执行此操作。
以下是我的代码

I am working a c# method which calls different methods based on some conditions and I am wondering if I can do this without switch or if else statements. Below is the code I have

if (msg== atype)
{
    _aHandler.HandleAType(msg, TopicType.A);
}
else if (msg== btype)
{
    _
    _btype.HandleBType(msg, TopicType.B);
}
else if (msg== ctype)
{
    _cHandler.HandleC(msg);
}
else if (msg== dtype)
{
    _dHandler.HandleDType(msg);
}

else
    _logger.Error($"No matching type found for {msg}");

请注意,在每种情况下,我有不同的方法和不同类型的参数。

Please note that I have different methods with different types of parameters in each condition.

有没有更好的方法可以在不使用switch / if-else的情况下做到这一点?

推荐答案

您的意思是这样的:

var dic = new Dictionary<string, Action>
{
    {atype, () => _aHandler.HandleAType(atype, TopicType.A)},
    {btype, () => _btype.HandleBType(btype, TopicType.B)},
    {ctype, () => _cHandler.HandleC(ctype)},
    {dtype, () => _dHandler.HandleDType(dtype)}
};

//Call it
dic[msg]();

这篇关于使用映射而不是switch / if else调用具有不同参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆