我正在制作一个“错误代码到字符串”转换器,它会根据其值显示错误代码的名称,例如0x000000c3
会给"Class not found"
,但使用我的OWN错误代码!< / p>
以下是它的实际情况:
#region errcodes
public int NORMAL_STOP = 0x00000000;
public int LIB_BROKEN = 0x000000a1;
public int RESOURCE_MISSING = 0x000000a2;
public int METHOD_NOT_FOUND = 0x000000a3;
public int FRAMEWORK_ERROR = 0x000000b1;
public int UNKNOWN = 0x000000ff;
#endregion
public string getName(int CODE)
{
}
我希望在函数string
中从参数CODE
获得getName
值。
我该怎么做?
答案 0 :(得分:6)
一个好的C#练习是使用枚举:
public enum ErrorCode
{
NORMAL_STOP = 0x00000000,
LIB_BROKEN = 0x000000a1,
RESOURCE_MISSING = 0x000000a2,
METHOD_NOT_FOUND = 0x000000a3,
FRAMEWORK_ERROR = 0x000000b1,
UNKNOWN = 0x000000ff
}
public const string InvalidErrorCodeMessage = "Class not found";
public static string GetName(ErrorCode code)
{
var isExist = Enum.IsDefined(typeof(ErrorCode), code);
return isExist ? code.ToString() : InvalidErrorCodeMessage;
}
public static string GetName(int code)
{
return GetName((ErrorCode)code);
}
另一个好建议:对错误代码使用C#命名约定会很棒:
public enum ErrorCode
{
NormalStop = 0x00000000,
LibBroken = 0x000000a1,
ResourceMissing = 0x000000a2,
MethodNotFound = 0x000000a3,
FrameworkError = 0x000000b1,
Unknown = 0x000000ff
}
用法示例:
void Main()
{
Console.WriteLine(GetName(0)); // NormalStop
Console.WriteLine(GetName(1)); // Class not found
Console.WriteLine(GetName(ErrorCode.Unknown)); // Unknown
}