You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法使用变量:CS0120错误,静态方法访问非静态字段问题

解决CS0120错误:静态方法无法访问非静态字段

错误原因

你遇到的CS0120错误,本质是静态方法GetAllWallpapers不能直接访问非静态成员assemblyPath。静态成员属于类本身,而非静态成员属于类的实例对象——静态方法执行时,类的实例可能还没创建,所以编译器不允许这种跨级别的访问。

两种可行解决方案

方案1:将assemblyPath改为静态字段

把assemblyPath声明为静态,让它和静态方法同属类级别:

public partial class Form1: Form
{
   // 加上static修饰符,转为静态字段
   private static string assemblyPath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location);

   private static string[] GetAllWallpapers(string daytime)
   {
      // 现在可以正常访问静态字段assemblyPath
      string dataPath = assemblyPath + @"..\..\..\..\data";
      // 补充你的后续逻辑,比如返回壁纸路径数组
      return new string[0];
   }
}

方案2:移除GetAllWallpapers的static修饰符

如果这个方法不需要保持静态,直接去掉static,让它成为实例方法,就能访问实例级别的assemblyPath:

public partial class Form1: Form
{
   private string assemblyPath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location);

   // 去掉static,转为实例方法
   private string[] GetAllWallpapers(string daytime)
   {
      string dataPath = assemblyPath + @"..\..\..\..\data";
      // 补充你的后续逻辑
      return new string[0];
   }
}

额外优化建议

路径拼接时推荐使用Path.Combine代替直接字符串拼接,它会自动处理不同操作系统的路径分隔符,避免潜在的路径错误:

string dataPath = Path.Combine(assemblyPath, @"..\..\..\..\data");

内容的提问来源于stack exchange,提问作者Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 19:20:36