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

为何仅第一个attributeConstructor方法被调用?C#代码问题求助

问题分析与解决方案

你遇到的问题是仅第一个attributeConstructor调用有输出,后续调用无响应,最可能的原因及解决方法如下:

1. 未处理用户输入导致程序阻塞

Main方法中提示输入目标等级,但没有读取输入的代码。如果Attribute构造函数依赖这个等级,且内部包含Console.ReadLine()之类的阻塞操作,程序会卡在第一次构造调用时,后续方法无法执行。

修复方式:
在Main中先读取并验证输入,再将等级传递给构造方法:

static void Main(string[] args)
{
    Console.WriteLine("Please enter a desired target level");
    int targetLevel = 1; // 默认等级
    // 读取并解析输入
    if (int.TryParse(Console.ReadLine(), out int inputLevel))
    {
        targetLevel = inputLevel;
    }
    else
    {
        Console.WriteLine("Invalid input, using default level 1");
    }

    // 传递等级给构造方法
    attributeConstructor("Charisma", targetLevel);
    attributeConstructor("Strength", targetLevel);
    attributeConstructor("Perception", targetLevel);
    attributeConstructor("Intelligence", targetLevel);
    attributeConstructor("Movement", targetLevel);
    attributeConstructor("Finesse", targetLevel);
    attributeConstructor("Willpower", targetLevel);
    attributeConstructor("Constitution", targetLevel);
}

// 修改方法接收等级参数
static void attributeConstructor(string attributeName, int targetLevel)
{
    Attribute attributePrintName = new Attribute(attributeName, targetLevel);
    Console.WriteLine(
        $"Attribute: {attributePrintName.name} Level: {attributePrintName.level} Modifier: {attributePrintName.modifier}"
    );
}

2. 属性构造时抛出未处理异常

如果后续某个属性(如Strength)在计算level或modifier时抛出异常,会导致程序直接终止,无法执行后续调用。

修复方式:
在attributeConstructor中添加异常捕获,确保单个属性处理失败不影响整体流程:

static void attributeConstructor(string attributeName)
{
    try
    {
        Attribute attributePrintName = new Attribute(attributeName);
        Console.WriteLine(
            $"Attribute: {attributePrintName.name} Level: {attributePrintName.level} Modifier: {attributePrintName.modifier}"
        );
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Failed to process {attributeName}: {ex.Message}");
    }
}

3. 构造函数中存在退出程序的逻辑

检查Attribute类的构造函数,确认没有Environment.Exit()或类似直接终止程序的代码,否则第一次调用后程序会直接退出。

辅助排查步骤

  • 提供完整的Attribute类代码,方便进一步定位问题。
  • 在每个attributeConstructor调用前添加调试输出(如Console.WriteLine($"Processing {attributeName}...")),确认程序是否执行到后续调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 21:23:07