在struct

时间:2016-02-29 15:18:22

标签: c#

我的代码是需要输出不同状态代码的服务,如下所示:

if(something is valid)
{
  if(this is found)
    return "200";
  else
    return 300;
}
else
   return "100";

有很多这样的状态代码,也会出现在应用程序的不同位置。所以,我想在一个地方将它们声明为常量并使用它们,以免硬编码字符串。

类似

public struct StatusCodes
{
  public static string 100 = "100";
  public static string 200 = "200";
}

并且能够将其用作

else return StatusCodes.100

是否有标准做法或好方法。

3 个答案:

答案 0 :(得分:5)

我建议使用枚举

  public enum Status {
    One = 100,
    Another = 200
  }

...

  if (some condition)
    return Status.One;
  else
    return Status.Another;

答案 1 :(得分:2)

这个怎么样:

public static class StatusCodes
{
  public const string Code100 = "100";
  public const string Code200 = "200";
}

您可以将其用作:

return StatusCodes.Code100

答案 2 :(得分:1)

在您的情况下(如果您确实有很多状态)创建一个包含公共字段的静态类更好:

  

public const string myStatus =" 100&#34 ;;

因此,您的状态将存储在一个位置。在那里你可以写MyClass.myStatus