如何将此if if结构转换为切换案例?

时间:2014-07-02 14:20:52

标签: c# if-statement switch-statement

我的IF Else结构

if (e.Exception.Message.Contains("'TierType' element is invalid"))
{
    objError.ErrorCode = "EC005";
    objError.ErrorMessage = "TierType is incorrect"; //constant file      
}

else if (e.Exception.Message.Contains("'Gender' element is invalid"))
{
    objError.ErrorCode = "EC010";
    objError.ErrorMessage = "Gender is incorrect"; //constant file    
}
else
{
    objError.ErrorCode = "EC050";
    objError.ErrorMessage = e.Exception.Message;//constant file                
}

我需要更改此结构以切换案例

e.Exception.Message.Contains(); //this contain 10 different values

我尝试按照它显示错误

string Exceptionmessage = e.Exception.Message;
switch (Exceptionmessage)
{
    case Exceptionmessage.Contains("'TierType' element is invalid"):
    //case "'TierType' element is invalid":
        objError.ErrorCode = "EC005";
        objError.ErrorMessage = "TierType is incorrect";
        break;
    default:
        objError.ErrorCode ="EC050";
        objError.ErrorMessage = e.Exception.Message;
        break;
}

我知道我尝试使用错误的方法。请告诉我如何根据我的要求编写开关结构。

1 个答案:

答案 0 :(得分:0)

正如在differents注释中所回答的那样,switch语句需要编译时常量,但是如果你想要一种替代方法,你可以创建一个类来初始化你将管理的不同异常的列表。

在此类中,您可以添加一个方法来处理异常或管理默认异常。

这是一种方法:

class Program
{
    public static void Main(string[] args)
    {
        try
        {
            throw new Exception("'Gender' element is invalid");
        }
        catch (Exception ex)
        {
            Error err = Error.ReadError(ex);
        }
    }
}

public class Error
{
    public string ErrorCode { get; set; }
    public string ErrorMessage { get; set; }
    public string ErrorRaw { get; set; }
    public static List<Error> ErrorList { get; private set; }

    static Error()
    {
        ErrorList = new List<Error>()
        {
            new Error(){
                ErrorCode = "EC005",
                ErrorMessage = "TierType is incorrect",  
                ErrorRaw = "'TierType' element is invalid"
            },
            new Error(){
                ErrorCode = "EC010",
                ErrorMessage = "Gender is incorrect",  
                ErrorRaw = "'Gender' element is invalid"
            },

        };
    }

    public static Error DefaultError(Exception ex)
    {
        return new Error(){
                ErrorCode = "EC050",
                ErrorMessage = ex.Message
            };
    }

    public static Error ReadError(Exception ex)
    {
        Error error = ErrorList.FirstOrDefault(e => ex.Message.Contains(e.ErrorRaw));
        if (error == null)
        {
            error = Error.DefaultError(ex);
        }

        return error;
    }
}