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

无法调用类中声明的成员变量?C#文本游戏开发求助

解决静态方法调用类成员变量的问题

你遇到的核心问题是:非静态成员变量(比如你的PlayerName)属于类的实例对象,而静态方法属于类本身,不依赖任何实例存在,所以静态方法里直接访问非静态变量会报错。要让多个方法共享这个变量,有两种常用方案:

方案一:把成员变量改成静态的

如果你的游戏是单玩家模式,直接把PlayerName声明为静态变量,这样它属于Program类本身,所有静态方法都能直接访问和共享它。修改后的代码如下:

class Program
{
    static string PlayerName; // 给变量添加static修饰符
    static void Main(string[] args)
    {
        GameTitle();
        ShowPlayerInfo(); // 其他静态方法也能直接调用PlayerName
    }
    static void GameTitle()
    {
        Console.WriteLine("Hello");
        Console.WriteLine("What's your name?");
        PlayerName = Console.ReadLine();
        Console.WriteLine("Welcome " + PlayerName + " to your new game!");
    }
    static void ShowPlayerInfo()
    {
        Console.WriteLine($"Current player: {PlayerName}");
    }
}

方案二:创建类的实例,用实例访问非静态变量

如果以后想扩展成多玩家模式,或者更贴合面向对象设计,建议使用实例变量。你需要先创建Program类的对象,再通过对象调用非静态方法和访问变量:

class Program
{
    string PlayerName; // 保持非静态变量
    static void Main(string[] args)
    {
        Program game = new Program(); // 创建类的实例
        game.GameTitle(); // 通过实例调用非静态方法
        game.ShowPlayerInfo(); // 其他方法也通过实例调用
    }
    void GameTitle() // 去掉static修饰符,改为非静态方法
    {
        Console.WriteLine("Hello");
        Console.WriteLine("What's your name?");
        PlayerName = Console.ReadLine();
        Console.WriteLine("Welcome " + PlayerName + " to your new game!");
    }
    void ShowPlayerInfo() // 非静态方法
    {
        Console.WriteLine($"Current player: {PlayerName}");
    }
}

小提示

  • 静态变量是全局共享的,整个程序运行期间只有一份值,适合单玩家场景;
  • 实例变量属于每个单独的对象,每个实例可以有自己的PlayerName,适合多玩家或需要多个游戏实例的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 01:31:04