简体   繁体   English

c# 中的字符串插值有什么问题?

[英]What am I doing wrong with string interpolation in c#?

What I am doing: I am trying to build a dictionary in one function ( DictionaryBuilder ), extract a string from said dictionary and apply variables to it in another function ( QuestionGenerator ).我在做什么:我试图在一个函数 ( DictionaryBuilder ) 中构建一个字典,从所述字典中提取一个字符串并在另一个函数 ( QuestionGenerator ) 中将变量应用于它。 Thus each time QuestionBuilder is called, the same string will be returned with differing contents without having to remake the same dictionary repeatedly.因此,每次调用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);
        }

Current results: "What is 0 x 0?"当前结果: “什么是 0 x 0?” and "The sum of 0 and 0 is 0".和“0和0的总和是0”。 I cannot get the new numbers to be applied.我无法应用新号码。

Question: How do I make this work so I can have the creation of the dictionary and the variables separate so as that each time QuestionGenerator is called a new question of the same format is provided without needing to repeatedly rebuild the dictionary (which I assume is very inefficient)?问题:我如何进行这项工作,以便我可以将字典的创建和变量分开,以便每次调用QuestionGenerator都会提供一个相同格式的新问题,而无需重复重建字典(我假设是效率很低)?

QuestionGenerator is called by the click of a button, so as to generate a new question in the same format. QuestionGenerator通过单击按钮调用,从而生成相同格式的新问题。

(Please note: The actual dictionary and calculations will be far larger, more complex and the questions and answers will not be in the same dictionary - this was just for example simplicity.) (请注意:实际的字典和计算会更大、更复杂,问题和答案不会在同一个字典中——这只是为了简单举例。)

You should turn questionDict into a dictionary with Functions as values, not strings:你应该把 questionDict 变成一个以函数作为值的字典,而不是字符串:

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}");
}

Then set your variables via call of those functions:然后通过调用这些函数来设置变量:

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

This allows you to capture the state of affairs (the values of a and b ) at the time you call the function.这允许您在调用函数时捕获事务状态( ab的值)。

Create a dictionary containing your string templates创建一个包含字符串模板的字典

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}");
}

and then use String.Format() on the retrieved string to compose your question.然后在检索到的字符串上使用String.Format()来撰写您的问题。

theQuestion = string.Format(questionDict["0"], a, b);

Note that the string are interpolated at the time of the DictionaryBuilder() call.请注意,字符串是在DictionaryBuilder()调用时插入的。 strings are not "dynamically" interpolated.字符串不是“动态”插值的。

When you create your dictionary, the strings are calculated once with the initial values at that time of a and b, that are both 0.创建字典时,会使用 a 和 b 时的初始值(均为 0)对字符串进行一次计算。

You would need to create a small one line method for that, you can for instance use a dictionary that stores a Func<string> instead of string.您需要为此创建一个小的单行方法,例如,您可以使用存储Func<string>而不是字符串的字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM