2

我正在构建一个应用程序来测试一些设备,该应用程序将有 43 个测试步骤(Step01.csStep43.cs)。(测试量很大,需要拆分成单独的文件)

在每个 .cs 文件中都有一个public static void Test(){}函数。

在任何给定点,用户都可以返回并重做测试,并且在每次测试结束时,都会询问用户是否要重做下一步(仅在之前已经完成的情况下)。如果从未完成下一步,则照常继续测试。

if (currentStep < maxStep )
{ 
    for(int i = currentStep; i < maxStep; i++)
    {
        _form1.testNumberComboBox.SelectedIndex = i - 1;

        if (MessageBox.Show($"{_form1.testNameComboBox.SelectedItem.ToString()} has already been tested.\nWould you like to retest?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
        {
            Step02.Test(_form1, sensor);
            return;
        }
    }
    _form1.testNumberComboBox.SelectedIndex = maxStep - 1;
}

我的问题是是否可以做这样的事情来调用我需要的测试,因为如果用户的回答是肯定的Step{i}.Test(_form1, sensor);,我真的不想这样做。if(i == 2){Step02.Test(_form1, sensor);}...if(i == 40){Step40.Test(_form1, sensor);}

不久前,我在 PHP 中做过类似的事情。有变量$acc1, $acc2 ... $accX并且能够在for(i) loop with ${"acc$i"}.

我不确定在 C# 中是否可行,这就是我要问的原因。(我是 C# 新手)

4

1 回答 1

2

您可以使用反射或使用Dictionary<string, Action>.

假设您有这样的测试类:

namespace MyTests
{    
    public class Test1
    {
        public static void Test() { }
    }
}

使用反射调用测试:

使用反射找到类和方法并调用它:

Assembly.GetExecutingAssembly().GetType("MyTests.Test1")
    .GetMethod("Test").Invoke(null, null);

使用 Dictionary<string, Action> 调用测试:

像这样初始化Dictionary<string, Action>()一次:

Dictionary<string, Action> tests = new Dictionary<string, Action>();
tests.Add("Test1", () => Test1.Test());
tests.Add("Test2", () => Test2.Test());

然后在需要时按名称调用:

tests["Test1"]();

结合反射和 Dictionary<string, Action>:

或者您可以将两者结合起来以获得更好的性能和更轻松的初始化。使用反射一次查找启​​动中的所有测试:

Dictionary<string, Action> tests = Assembly.GetExecutingAssembly().GetTypes()
    .Where(t => t.FullName.StartsWith("MyTests.Test"))
    .Select(t => t.GetMethod("Test"))
    .ToDictionary(m => m.DeclaringType.Name,
        m => new Action(() => m.Invoke(null, null)));

随时运行:

tests["Test1"]();
tests["Test2"]();
于 2020-01-30T10:40:30.433 回答