跨.cake文件共享全局变量

时间:2017-09-29 10:34:46

标签: c# cakebuild

我使用CAKE 0.21.1.0。

我的build.cake脚本加载了另一个.cake脚本:tests.cake

我在build.cake中定义了一些全局变量,我想在我的.cake脚本中使用这些变量。

假设我有一个名为testDllPath的全局变量。

当我在testDllPath中使用tests.cake时,我看到以下错误:

  

错误CS0120:非静态字段,方法或属性'testDllPath'

需要对象引用

如果我尝试在testDllPath中声明一个名为tests.cake的新变量,我会看到此错误:

  

错误CS0102:类型'提交#0'已经包含'testDllPath'的定义

如何从另一个build.cake文件访问.cake中定义的全局变量?

1 个答案:

答案 0 :(得分:2)

如果在声明后加载它,请单击。

即。这不会起作用

foreach(string line in mylistA.Intersect(mylistB, StringComparer.InvariantCultureIgnoreCase))
     ResultsToDocument(); // does this make sense, not passing the line?

这将起作用

#load "test.cake"
FilePath testDLLPath = File("./test.dll");

更优雅的方法可能是将文件包含公共变量并首先加载,即

FilePath testDLLPath = File("./test.dll");
#load "test.cake"

如果您尝试从静态方法或类中访问本地变量,则由于范围界定而无法工作。

在这些情况下,您有一些选择

  1. 将变量传递给方法
  2. 传递变量类构造函数
  3. 使用可从任何地方访问的公共静态属性/字段。
  4. 静态/参数使用我们的优势是加载顺序无关紧要。

    示例局部变量静态方法

    #load "parameters.cake"
    #load "test.cake"
    

    示例将变量传递给构造函数

    File testDLLPath = File("./test.dll");
    
    RunTests(testDLLPath);
    
    public static void RunTests(FilePath path)
    {
        // do stuff with parameter path
    }
    

    静态属性示例

    File testDLLPath = File("./test.dll");
    
    var tester = new Tester(testDLLPath);
    
    tester.RunTests();
    
    
    public class Tester
    {
       public FilePath TestDLLPath { get; set; }       
    
       public void RunTests()
       {
           //Do Stuff accessing class property TestDLLPath
       }
    
       public Tester(FilePath path)
       {
            TestDLLPath = path;
       }
    }
    
相关问题