3

Is it theoretically possible to lookup the consts in a class at runtime?

I have a static class full of consts similar to this:

public static class Constants {
    public const string Yes = "Yes";
    public const string No = "No";
}

and I was wondering if I could create a UnitTest that could take the Constants class, and read all of the consts from within it. The idea being, I could write one unit test, that is then run against all of the const strings. So if I add more string to the class, the unit test does not have to change.

I believe the answer here is no... but thought it was worth asking just in case!

4

2 回答 2

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);
}
于 2013-07-24T15:03:11.967 回答
2

使用反射,您可以使用IsLiteral字段的属性来确定它是否为常量:

var consts = myType.GetFields(BindingFlags.Static | BindingFlags.Public).Where(fld => fld.IsLiteral);

然后,您可以在单元测试中根据需要执行这些操作。

于 2013-07-24T15:02:46.500 回答