首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >允许用户在c#中定义字符串

允许用户在c#中定义字符串
EN

Stack Overflow用户
提问于 2013-03-13 08:42:08
回答 5查看 611关注 0票数 1

我问的是一个非常常见的特性,我找不到任何关于。我希望允许我的程序的用户使用程序中的变量创建自定义字符串。

示例:

我有一份清单:

代码语言:javascript
运行
复制
ID   Name     Description       Value      Status
0    name 0   beschreibung 0    Wert 0     Status 0
1    name 1   beschreibung 1    Wert 1     Status 1
2    name 2   beschreibung 2    Wert 2     Status 2
3    name 3   beschreibung 3    Wert 3     Status 3
4    name 4   beschreibung 4    Wert 4     Status 4
5    name 5   beschreibung 5    Wert 5     Status 5
6    name 6   beschreibung 6    Wert 6     Status 6
7    name 7   beschreibung 7    Wert 7     Status 7
8    name 8   beschreibung 8    Wert 8     Status 8
9    name 9   beschreibung 9    Wert 9     Status 9

现在,用户将能够定义以下自定义字符串:

Id {ID}的项的名称是{ Name }。它的描述是{ Description }。它具有值{ Value }和状态{ Status }。

我可以为这些字符串编写一个自定义解析例程,但我希望为该任务找到一个标准解决方案。有什么建议吗?

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2013-03-13 09:01:45

您可以允许用户在字符串中使用指定的“变量”。例如:

代码语言:javascript
运行
复制
var userstring = "The Name of the Item with the Id {ID} is {Name}. It's Description is {Description}. It has the Value {Value} and the Status {Status}.";
var result = userstring.Replace("{ID}", Id).Replace("{Name}", Name).Replace("{Description}", Description).Replace("{Value}", Value).Replace("{Status}", Status);
票数 0
EN

Stack Overflow用户

发布于 2013-03-13 08:44:55

C# (以及一般情况下的.NET )中字符串格式的标准解决方案是使用String.Format方法。例如,你可以:

代码语言:javascript
运行
复制
string reult = string.Format("The Name of the Item with the Id {0} is {1}. It's Description is {2}. It has the Value {3} and the Status {4}.",
       id, name, description, value, status);
票数 3
EN

Stack Overflow用户

发布于 2013-03-13 08:47:24

我怀疑您希望用对象列表中的值替换占位符,如{ID}{Name}。您可以使用带有模式的正则表达式,例如

代码语言:javascript
运行
复制
\{(?<key>[A-Za-z]+)\}

它将查找{something}的所有实例,并允许您提取something以便从列表中获取值。

使用Regex.Match的重载(接受输入字符串和MatchEvaluator委托)将允许您获得正确的值:

代码语言:javascript
运行
复制
var myObject = new Dictionary<string,string>(){
    {"ID","1"},  
    {"Name","Bob Jones"},
    {"Description","A very nice man"},
    {"Value","1000"},
    {"Status","New"},
};
var regex = new Regex(@"\{(?<key>[A-Za-z]+)\}");
var input = "The Name of the Item with the Id {ID} is {Name}. It's Description is {Description}. It has the Value {Value} and the Status {Status}.";
string result = regex.Replace(input, m => myObject[m.Groups["key"].Value]);

Console.WriteLine(result);

实例:http://rextester.com/FLGTQW95860

该示例中的字典只是为了演示regex的用法--没有理由不可能是DataRow或自定义对象,或者属性的任何其他容器。

当然,此解决方案不包含任何错误处理(例如不存在属性的占位符),如果允许用户指定字符串,我怀疑您会希望包括这些错误处理。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15380463

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档