开发者

Calling different methods depending on enum value without using switch

I have the following code:

public void ParseNetworkPacket(IAsyncResult iResult)
    {
        NetworkConnection networkConnection = (NetworkConnection)iResult.AsyncState;

        string teste = NetworkPacketType.ToString();

        switch (this.NetworkPacketType)
        {
            case NetworkPacketType.ShotPacket:
                break;
            case NetworkPacketType.ShotResponsePacket:
                break;
            case NetworkPacketType.ChatMessagePacket:
                break;
            default:
                break;
        }

        networkConnection.BeginReadPacket();
    }

NetworkPacketType is a enum defined by me. In the switch, depending on the type of the enum, I would call开发者_如何学C a different method. I would like to do that not using switch, because I may have too many enum types. Is there any other way to do that? Or wih an enum that's the only possible way?


Beside using a map as suggested in the answer linked by Veer, you could also use reflection. If you would name your methods like the enum values for example, it could be done like this:

public void ParseNetworkPacket(IAsyncResult iResult)
    {
        NetworkConnection networkConnection = (NetworkConnection)iResult.AsyncState;

        string teste = NetworkPacketType.ToString();

        string methodName = this.NetworkPacketType.ToString();

        MethodInfo methodInfo = GetType().GetMethod(methodName, 
            BindingFlags.Instance | BindingFlags.NonPublic);

        methodInfo.Invoke(this, /* your arguments here */);

        networkConnection.BeginReadPacket();
    }

private void ShotPacket() 
{
    ....
}

But I would not really recommend this approach if not absolutely neccessary. It can be a pain to maintain this, among other things.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜