Lookup在运行时在类中构成

Nic*_*ick 3 c# unit-testing

它是理论上可以在查找constsclass运行时?

我有一个充满类似于此的consts的静态类:

public static class Constants {
    public const string Yes = "Yes";
    public const string No = "No";
}
Run Code Online (Sandbox Code Playgroud)

我想知道我是否可以创建一个可以接受Constants类的UnitTest,并从中读取所有的consts.我的想法是,我可以编写一个单元测试,然后针对所有的const字符串运行.因此,如果我在类中添加更多字符串,则单元测试不必更改.

我相信这里的答案是否定的......但我认为值得一提以防万一!

Hen*_*ing 5

尝试这样的事情:

var t= typeof(Constants).GetFields(BindingFlags.Static | BindingFlags.Public)
                    .Where(f => f.IsLiteral);
foreach (var fieldInfo in t)
{
   // name of the const
   var name = fieldInfo.Name;

   // value of the const
   var value = fieldInfo.GetValue(null);
}
Run Code Online (Sandbox Code Playgroud)