【问题标题】:How to extract a dynamic object from a variable template string and merge it in again?如何从变量模板字符串中提取动态对象并再次合并?
【发布时间】:2023-03-25 06:27:01
【问题描述】:

我有一个字符串。

此字符串是在运行时从文件中提取的,可以是任何格式,如下例所示。

唯一的规则是括号内的单词必须转换为dynamic 对象上的属性,并且它是向用户询问的值,可能使用winforms PropertyGridObjectListView。然后将用户的答案合并到字符串模板中(可能使用FormattableStringFactory.Create ?)。

示例字符串:

string template = "The client name is {name} and the client's age is {age}";
string template2 = "This house is on {streetName} and the door number is {doorNumber}";

对象提取:

dynamic templateObject = objectExtractor (templateString);

最终字符串(用户将数据引入templateObject后):

string result = "The client name is John and the client's age is 25";

换句话说,我想做的类似于 C# 6 编译器使用字符串插值语法糖所做的事情。

我正在寻找一种方法(最好是一种简单的通用方法),但我自己无法弄清楚,并且在进行了广泛的谷歌搜索后也没有找到它。

【问题讨论】:

    标签: c# string winforms dynamic


    【解决方案1】:

    字符串插值是 String.Format 的不同形式。
    您可以将 template 字符串中的元素替换为带编号的占位符,并使用 String.Format() 使用由用户输入确定的替换占位符的值数组来格式化字符串:

    int matchCount = 0;
    string temp = Regex.Replace(template, @"\{.*?\}", (Match m)=> $"{{{matchCount++}}}");
    string result = string.Format(temp, new[] {input1, input2});
    

    其中new[] {input1, input2} 表示用作替换的输入数组。
    当然可以预先构建值数组:

    var userInputs = new string[] { input1, input2, inputN };
    string result = string.Format(temp, userInputs);
    

    那么这取决于你的objectExtractor 是如何工作的。您可以使用 Regex.Matches 以相同的模式从模板字符串中提取原始占位符并确定输入的数量及其类型,这可以基于每个占位符的名称,例如使用 Dictionary<string, Control>将字符串选择器映射到输入控件或其他任何内容。

    例如,使用字典来映射占位符和 TextBox 控件:

    var maps = new Dictionary<string, Control>() {
        ["{name}"] = textBox1,
        ["{age}"] = textBox2,
    };
    
    string[] parameters = 
        Regex.Matches(template, @"\{.*?\}").OfType<Match>().Select(m => m.Value).ToArray();
    
    string[] userInputs = parameters.Select(s => maps[s].Text).ToArray();
    string result = string.Format(temp, userInputs);
    

    【讨论】:

    • 谢谢。我正在尝试您的解决方案。当我完成并测试它时,我会接受答案。很抱歉长时间等待我的反馈。
    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2020-12-02
    • 1970-01-01
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多