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

C#控制台应用调用Action[]数组方法时输出System.Action[]的问题

解决Action数组调用时显示System.Action[]的问题

你的问题核心是误将Action委托对象直接作为字符串输出,而没有执行委托里的方法。C#中直接拼接委托对象到字符串时,会调用它的ToString()方法,返回类型全称(比如System.Action),所以控制台才会显示这个内容,而不是你想要的问题文本。

快速修复方案

修改循环内的代码,执行Action委托而不是输出它:

for (k = 0; k < testThree.Length; k++)
{
    Console.WriteLine("\n" + (i + (j + (k + 1))) + ". ");
    testThree[k].Invoke(); // 等价于直接写 testThree[k]();
    testThreeInput[k] = Console.ReadLine();                              
}

这样会执行每个Action对应的方法,输出预设的问题文本。

更贴合你需求的优化方案

如果你希望序号和问题文本在同一行输出,可以改用Func<string>数组(返回字符串的委托),调整方法返回问题文本而非直接输出:

// 改用Func<string>数组存储返回字符串的委托
Func<string>[] testThree = new Func<string>[]
{ 
    () => testThreeQuestionOne(),
    () => testThreeQuestionTwo() 
};

// 修改方法为返回字符串
static string testThreeQuestionOne()
{
    return "What is the output of: Console.WriteLine(\"asd\");";
}

static string testThreeQuestionTwo()
{
    return "What is the output of: Console.WriteLine(\"lol\");";
}

// 循环内直接拼接序号和返回的问题文本
for (k = 0; k < testThree.Length; k++)
{
    Console.WriteLine("\n" + (i + (j + (k + 1))) + ". " + testThree[k]());
    testThreeInput[k] = Console.ReadLine();                              
}

这样既保留了用数组管理问题的思路,又能实现你预期的输出格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 04:48:22