c# - 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
通过单击按钮调用,以生成相同格式的新问题。
(请注意:实际的字典和计算会更大、更复杂,而且问题和答案不会在同一个字典中——这只是为了简单起见。)
解决方案
您应该将 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"]();
这允许您在调用函数时捕获事务状态( 和 的值a
)b
。
推荐阅读
- c - 根据面积对n个三角形的边进行排序
- android - 从资产文件夹复制数据库后,android pie 中没有此类表错误
- javascript - 为什么我的 window.setInterval 函数在多次调用时会在 DOM 中重叠?
- c - 如何从字符串中删除第一个单词并在 C 中保留句子的其余部分?
- c++ - 使用 QRegularExpression 提取双引号内的字符串
- javascript - 来自 mouseenter 事件的滚动元素的 pageY?
- haskell - 为什么这个 unsafeCoerce 不是不安全的?
- javascript - 如何使用 webpack 连接和捆绑 JS 文件以加载到脚本标签中
- python - 如果转置索引具有重复值,则创建新行
- tree - 在 PROLOG 中查找二叉树中的元素