如何在方法之外验证条件

How to verify condition outside of a method

有没有办法在代码中创建 class 变量 时验证它的完整性?

例如,我创建并初始化了一个 class 成员变量,如下所示:

public class MyClass
{
  public static Dictionary<MyEnum, int> SomeDictionary = new Dictionary<MyEnum, int> {
            { MyEnum.First, 9 },
            { MyEnum.Second, 7 },
            { MyEnum.Third, 17 }
  };

  // This obviously doesn't compile
  Debug.Assert(<SomeDictionary contains good stuff>);

  // Some method in my class
  public void SomeMethod()
  {
    // I could use something like this in this method to verify
    // the integrity of SomeDictionary, but I'd rather do this
    // at the point (above) where SomeDictionary is defined.
    Contract.Requires(<SomeDictionary contains expected stuff>);
  }
}

正如我在代码中指出的那样,我想在 "class" 范围内验证我的数据内容,但是 Debug.AssertContract.Requires 仅在方法(或 属性) 范围。

编辑: 这个问题最初使用一个列表,其内容与一个枚举(切向)相关,但人们关注的是该列表是如何从一个枚举派生的,而不是如何验证列表内容的问题。所以我完全重写了这个问题来澄清这个问题是关于验证的,而不是关于构建数据结构的。

如果您声明它是在项目的其他地方定义的类型,您可以从枚举中创建列表。

using System.Linq;

enum Stuff
{
  UglyStuff,
  BrokenStuff,
  HappyStuff
}

public class MyStuff
{
  public static List<string> MyList => System.Enum.GetNames(typeof(Stuff)).ToList();
}

这就够了吗? https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

Static constructors are also a convenient place to enforce run-time checks on the type parameter that cannot be checked at compile-time via constraints (Type parameter constraints).

A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.

但是单元测试可以做得更好。如果不是因为它们离代码很远,必须单独编写和维护。但至少它们没有运行时开销。