首页 > 解决方案 > c# 中的字符串插值我在做什么错?

问题描述

我在做什么:我正在尝试在一个函数()中构建一个字典,从所述字典中提取一个字符串并在另一个函数( )DictionaryBuilder中将变量应用于它。QuestionGenerator因此,每次QuestionBuilder调用时,都会返回具有不同内容的相同字符串,而无需重复重新制作同一个字典。

        int a;
        int b;
        string theQuestion;
        string theAnswer;
        Dictionary<string, string> questionDict = new Dictionary<string, string>();

        void DictionaryBuilder()
        {
            questionDict.Add("0", $"What is {a} x {b} ?");
            questionDict.Add("1", $"The sum of {a} x {b} = {a*b}");
        }

        void QuestionGenerator()
        {
            Random rnd = new Random();
            a = rnd.Next(1, 10);
            b = rnd.Next(1, 10);
            theQuestion = questionDict["0"];
            theAnswer = questionDict["1"];
            Console.WriteLine(theQuestion);
            Console.WriteLine(theAnswer);
        }

当前结果: “什么是 0 x 0?” 和“0和0之和为0”。我无法获得要应用的新号码。

问题:如何进行这项工作,以便我可以创建字典并将变量分开,以便每次QuestionGenerator调用一个相同格式的新问题,而无需重复重建字典(我认为这是非常效率低下)?

QuestionGenerator通过单击按钮调用,以生成相同格式的新问题。

(请注意:实际的字典和计算会更大、更复杂,而且问题和答案不会在同一个字典中——这只是为了简单起见。)

标签: c#stringstring-interpolation

解决方案


您应该将 questionDict 转换为以 Functions 作为值而不是字符串的字典:

Dictionary<string, Func<string>> questionDict = new Dictionary<string, Func<string>>();

void DictionaryBuilder()
{
    questionDict.Add("0", () => $"What is {a} x {b} ?");
    questionDict.Add("1", () => $"The sum of {a} x {b} = {a*b}");
}

然后通过调用这些函数来设置变量:

theQuestion = questionDict["0"]();
theAnswer = questionDict["1"]();

这允许您在调用函数时捕获事务状态( 和 的值ab


推荐阅读