C#方法作为变量

本文关键字:变量 方法 | 更新日期: 2023-09-27 18:22:15

我在带有Selenium的C#Visual Studio中有测试代码。我有几个测试类和一个实用程序类。

using ...
namespace Test
{
    [TestClass]
    public void Test1()
    {
        //CODE
    }
    [TestClass]
    public void Test2()
    {
        //CODE
    }
    [TestClass]
    public void Test3()
    {
        //CODE
    }
    [TestClass]
    public void Utility()
    {
        IWebDriver driver;
        int a,b,c;
        string name, password;
        srting[] info = {"a","b","c"};
        //other variables
    }
}

我的问题很简单(有几个类似的问题,但它们对我来说不起作用,就像动态分配方法/方法作为变量中的decation一样)。有没有可能从类Utility中的变量创建方法,将它们作为变量在其他类中使用,而不必一直复制它们?或者我还能为此做些什么?

寻求帮助
Janer

C#方法作为变量

四人帮青睐的一个解决方案是"偏爱组合而非继承",它采用以下方式:

[TestClass]
public void Test3()
{
    //CODE
}
[TestClass]
public void Utility()
{
    IWebDriver driver;
    int a,b,c;
    string name, password;
    srting[] info = {"a","b","c"};
    //other variables
}

并将其转换为:

[TestClass]
public void Test3()
{
    var utility = new Utility();
    //do the test
}

新的实用程序类看起来是这样的:

 public class Utility()
 {
    IWebDriver driver {get;set;}
    int a {get;set; int b {get;set;} int c {get;set;};
    string name {get;set;} string password {get;set;}
    string[] info {get{return new string[]{"a","b","c"}};
    //other variables
 }