gpt4 book ai didi

C# 按值查找变量

转载 作者:行者123 更新时间:2023-11-30 14:29:10 25 4
gpt4 key购买 nike

我正在制作一个“错误代码到字符串”转换器,它会根据错误代码的值显示错误代码的名称,例如 0x000000c3 会给出 “Class not found”,但使用我自己的错误代码!

实际情况如下:

#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)
{

}

我想从函数 getName 中的参数 CODE 获取一个 string 值。

我该怎么做?

最佳答案

一个好的 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
}

关于C# 按值查找变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076751/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com