【问题标题】:How to create a static class of integers?如何创建一个静态整数类?
【发布时间】:2021-02-01 14:38:07
【问题描述】:

首先,我可以在 Windows 窗体中调用一个示例:

Color.Red;  

然后得到一个哈希值。我正在寻找的是有一个 ErrorLevel 类,它具有以下内容:

ErrorLevel.Warning

它只是返回一个值为 0、1 等的整数。

我对静态类、接口等有很好的了解。

我对如何执行此操作的替代方法不感兴趣,例如某些控制台类已经具有此功能,因为我想了解此主题。

它的名字也可以帮助我进行谷歌搜索/在线教程。

现在我正在搞砸这个,但不知道我在做什么。

internal class ErrorLevel
{
    public static ErrorLevel Error { get; }
    public static ErrorLevel Warning { get; }
    public static ErrorLevel Info { get; }
}

【问题讨论】:

标签: c# static integer


【解决方案1】:

在您的班级中,ErrorLevel 包含三个 ErrorLevels。其中每一个都包含什么?它们将包含三个ErrorLevels。每个都包含三个ErrorLevels...从来没有实际值。

最简单的,听起来你在描述enum

public enum ErrorLevel
{
    Error,
    Warning,
    Info
}

但是,如果您想要更自定义的功能,例如您描述的功能,那么请专注于您所描述的内容:

然后得到一个哈希值

所以属性值为string。如果您的属性应该是字符串,请将它们设为:

internal class ErrorLevel
{
    public static string Error { get; } = "Error";
    public static string Warning { get; } = "Warning";
    public static string Info { get; } = "Info";
}

甚至可能只是常量值:

internal class ErrorLevel
{
    public const string Error = "Error";
    public const string Warning = "Warning";
    public const string Info = "Info";
}

【讨论】:

  • 这详细回答了我所有的问题,非常感谢 - 我会在冷却时间结束时将其标记为。
  • 或者只使用const strings的字段:public const string Error = "Error";
【解决方案2】:

为什么不使用enumeration

public enum ErrorLevel 
{ 
  Error, 
  Warning,
  Info
}

你可以使用这样的东西来获取字符串:

var level = ErrorLevel.Warning; // 1

string str = level.ToString();  // "Warning"

当然,您也可以使用具有 consts 的静态类:

static public class ErrorLevel
{
  public const int Error = 0;
  public const int Warning = 1;
  public const int Info = 2;
}

但似乎枚举更适合您的目的,除非您需要更大的灵活性或需要更改值(不再有 const):

static public class ErrorLevel
{
  static public int Error = 0;
  static public int Warning = 1;
  static public int Info = 2;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2021-02-26
    • 2012-11-26
    • 2015-08-13
    • 2011-09-29
    相关资源
    最近更新 更多