简化方法? [英] Simplifying a method?

查看:43
本文介绍了简化方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近接手了一个项目,作为个人爱好,以挑战提高我的代码质量.我已经做了这个方法,但我觉得我肯定在某种程度上已经过度使用它了,我觉得有一种非常简单的方法可以做到,而不必像这样运行一个大开关??

I've recently took over a project as a personal hobby in a challenge to improve my code quality. I had made this method but I feel like I'm definitely over working it in some way, I feel like there's a really simple way to do it without having to run through a large switch like this??

我知道 0-9 可能只是 .ToString() 'd 然后解析为 int 并返回,但我不确定如何合并这个想法,同时还要考虑其余的切换案例.

I know the 0-9 could just be .ToString()'d and then parsed to int and returned, but I'm unsure how to merge that idea whilst also considering the rest of the switch cases.

public static short ParseHeight(char input)
{
    switch (input)
    {
        case '0':
            return 0;
        case '1':
            return 1;
        case '2':
            return 2;
        case '3':
            return 3;
        case '4':
            return 4;
        case '5':
            return 5;
        case '6':
            return 6;
        case '7':
            return 7;
        case '8':
            return 8;
        case '9':
            return 9;
        case 'a':
            return 10;
        case 'b':
            return 11;
        case 'c':
            return 12;
        case 'd':
            return 13;
        case 'e':
            return 14;
        case 'f':
            return 15;
        case 'g':
            return 16;
        case 'h':
            return 17;
        case 'i':
            return 18;
        case 'j':
            return 19;
        case 'k':
            return 20;
        case 'l':
            return 21;
        case 'm':
            return 22;
        case 'n':
            return 23;
        case 'o':
            return 24;
        case 'p':
            return 25;
        case 'q':
            return 26;
        case 'r':
            return 27;
        case 's':
            return 28;
        case 't':
            return 29;
        case 'u':
            return 30;
        case 'v':
            return 31;
        case 'w':
            return 32;
        default:
            throw new FormatException("The input was not in a correct format: input must be between (0-k)");
    }
}

推荐答案

你可以这样做

var value = "0123456789abcdefghijklmnopqrstuvwxyz".IndexOf(input);
if (value == -1)
    throw new FormatException("The input was not in a correct format: input must be between (0-k)");
return value;

这篇关于简化方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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