Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/312.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# 跨.cake文件共享全局变量_C#_Cakebuild - Fatal编程技术网

C# 跨.cake文件共享全局变量

C# 跨.cake文件共享全局变量,c#,cakebuild,C#,Cakebuild,我用蛋糕0.21.1.0 我的build.cake脚本加载另一个.cake脚本:测试.cake 我在build.cake中定义了一些全局变量,我希望在和脚本中都使用这些变量 假设我有一个名为testDllPath的全局变量 在tests.cake中使用testDllPath时,我看到以下错误: 错误CS0120:非静态字段、方法或属性“testDllPath”需要对象引用 如果我试图在tests.cake中声明一个名为testDllPath的新变量,我会看到以下错误: 错误CS0102:类型“S

我用蛋糕0.21.1.0

我的
build.cake
脚本加载另一个
.cake
脚本:
测试.cake

我在
build.cake
中定义了一些全局变量,我希望在
脚本中都使用这些变量

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

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

错误CS0120:非静态字段、方法或属性“testDllPath”需要对象引用

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

错误CS0102:类型“Submission#0”已包含“testDllPath”的定义


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

如果在声明后加载它,则是

也就是说,这行不通

#load "test.cake"
FilePath testDLLPath = File("./test.dll");
这会奏效的

FilePath testDLLPath = File("./test.dll");
#load "test.cake"
一种更优雅的方法可能是使用带有公共变量的文件,并首先加载该文件,即

#load "parameters.cake"
#load "test.cake"
如果您试图从静态方法或类访问局部变量,由于作用域的原因,这将无法工作

在这些情况下,您有几个选择

  • 将变量传递给方法
  • 传递变量类构造函数
  • 使用可以从任何地方访问的公共静态属性/字段
  • 静态/参数使用的优点是加载顺序无关紧要

    局部变量静态法示例 将变量传递给构造函数的示例 静态属性示例
    谢谢你的回复,德夫里德!声明全局变量后,我加载了
    tests.cake
    ,但仍然看到错误消息
    error CS0120:非静态字段、方法或属性“testDllPath”需要对象引用。
    。如果在类或静态方法中使用它,则需要将其指定为该方法的参数,或者将其作为类上的公共静态属性/字段。如果你这样做,加载顺序将不重要,这是一个很好的加号。你可以在这里看到一个例子:
    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;
       }
    }
    
    BuildParams.TestDLLPath  = File("./test.dll");
    
    RunTests();
    
    
    public static void RunTests()
    {
        // do stuff with BuildParams.TestDLLPath
    }
    
    public static class BuildParams
    {
       public static FilePath TestDLLPath { get; set; }    
    }