静态字段失败,因为编译器认为它是非静态的

Static field fails because compiler thinks its non-static

在编写 Cake 插件时,我有以下内容:

public static class Aliases
{
[CakeMethodAlias]
public static VaultInfo GetVaultInfo(this ICakeContext context, string userName)
{
    Debugger.Launch();
    return new VaultInfo("","","","","");
} 
}

在我的脚本中 build.cake 我有:

private static VaultInfo r = GetVaultInfo("user");

当我 运行 这个与 Cake.exe build.cake 我得到

Error: <path>/setup.cake(10,30): error CS0120: An object reference is required for the non-static field, method, or property 'GetVaultInfo(string)'

听起来蛋糕脚本中明显有问题但是...!

我从未使用过 cake,但我可以告诉你,你所拥有的不是有效的 C#。您的方法设置为扩展方法,但您正试图从静态上下文中调用它。

把它改成这个,它应该可以工作,而且看起来你并没有在方法中使用 ICakeContext。

[CakeMethodAlias]
public static VaultInfo GetVaultInfo(string userName)
{
    Debugger.Launch();
    return new VaultInfo("","","","","");
}

如果您确实需要 ICakeContext,则必须在 ICakeContext 的实例上调用该方法 class。

从您的字段中删除静态修饰符。

而不是

private static VaultInfo r = GetVaultInfo("user");

改为

private VaultInfo r = GetVaultInfo("user");

请记住适用标准 C# 规则,静态变量在调用任何实例之前初始化。 (或者我相信)