Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 运行时在类中查找常量_C#_Unit Testing - Fatal编程技术网

C# 运行时在类中查找常量

C# 运行时在类中查找常量,c#,unit-testing,C#,Unit Testing,在运行时,理论上是否可以在类中查找常量 我有一个充满常量的静态类,类似于: public static class Constants { public const string Yes = "Yes"; public const string No = "No"; } 我想知道是否可以创建一个UnitTest,它可以接受Constants类,并从中读取所有常量。我的想法是,我可以编写一个单元测试,然后对所有常量字符串运行。因此,如果我向类中添加更多字符串,单元测试就不必更改

在运行时,理论上是否可以在
类中查找
常量

我有一个充满常量的静态类,类似于:

public static class Constants {
    public const string Yes = "Yes";
    public const string No = "No";
}
我想知道是否可以创建一个UnitTest,它可以接受Constants类,并从中读取所有常量。我的想法是,我可以编写一个单元测试,然后对所有常量字符串运行。因此,如果我向类中添加更多字符串,单元测试就不必更改


我相信答案是否定的。。。但我觉得这值得一问,以防万一

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

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

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

尝试以下操作:

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);
}

查看反射(常量的特定示例:)您将针对常量编写什么类型的单元测试?上面的类很简单,但在实际代码中,常量引用正则表达式字符串,我们希望在编译时测试这些字符串是否有效。如果您的类包含正则表达式而不仅仅是正则表达式字符串,它们不是都会在编译时自动进行有效性测试吗?是的,它们会,但我们会在内存中有几千个正则表达式实例,而不是几千个字符串。我可能弄错了,但据我回忆,
IsLiteral
也为
readonly
字段提供了真值,因此,您需要测试
!fld.IsInitOnly
将其过滤掉。替换了。用一个;在第一行的末尾,但除此之外,我们逐字使用了这段代码。谢谢