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

C#报错CS0103:对象不存在于当前上下文如何解决?

错误原因

你触发CS0103错误的核心原因是C#的变量作用域规则:在if/else分支的大括号内部声明的变量,仅在当前分支的代码块内有效,跳出分支后就会被回收,无法被外部的while循环访问。

修复方案

步骤1:为三个自定义类定义公共基类/接口

你的Hamburgler、Ronald、Kids三个类都包含相同的属性(Name、PlayerId、Health)和方法(Fight()),先提取公共部分定义抽象基类,三个类继承该基类即可:

// 公共抽象基类
public abstract class PlayerBase
{
    public string Name { get; set; }
    public int PlayerId { get; set; }
    public int Health { get; set; }
    public abstract int Fight();
}

// 三个子类继承基类,保留原有业务逻辑
public class Hamburgler : PlayerBase
{
    public override int Fight()
    {
        // 此处保留你原有Fight方法的实现逻辑
    }
}

public class Ronald : PlayerBase
{
    public override int Fight()
    {
        // 此处保留你原有Fight方法的实现逻辑
    }
}

public class Kids : PlayerBase
{
    public override int Fight()
    {
        // 此处保留你原有Fight方法的实现逻辑
    }
}

步骤2:调整变量声明位置

在if/else分支外部提前声明playerTwo变量,在分支内部仅做赋值操作即可:

// 分支外层提前声明playerTwo,类型为公共基类
PlayerBase playerTwo;

if(p2 == 1)
{
    playerTwo = new Hamburgler(){Name = name, PlayerId = playerCount, Health = 100};
    Console.WriteLine("Hamburgler Chosen!");
    Console.ReadKey();
}
else if(p2 == 2)
{
    playerTwo = new Ronald(){Name = name, PlayerId = playerCount, Health = 100};
    Console.WriteLine("Ronald McDonald Chosen!");
    Console.ReadKey();
}
else if (p2 ==3)
{
    playerTwo = new Kids(){Name = name, PlayerId = playerCount, Health = 100};
    Console.WriteLine("Fry Kids Chosen!");
    Console.ReadKey();
}
else 
{
    playerTwo = new Hamburgler(){Name = name, PlayerId = playerCount, Health = 100};
    Console.WriteLine("Invalid Input. Defaulting as Hamburgler");
    Console.ReadKey();
}

// 后续while循环可正常访问playerTwo变量
while (playerOne.Health > 0 || playerTwo.Health > 0)
{
    int atk1 = playerOne.Fight();
    playerTwo.Health = playerTwo.Health - atk1;
    int atk2 = playerTwo.Fight();
    playerOne.Health = playerOne.Health - atk2;
}

补充说明:如果暂时不想调整类的继承结构,也可以把外层声明的playerTwo类型改为dynamic,但该方案会丢失编译时类型校验,容易触发运行时错误,不推荐新手使用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:24:05