我有一个XML文件,我希望允许最终用户设置字符串的格式。
例如:
<Viewdata>
<Format>{0} - {1}</Format>
<Parm>Name(property of obj being formatted)</Parm>
<Parm>Phone</Parm>
</Viewdata>
在运行时,我需要以某种方式将其转换为 String.Format("{0} - {1}", usr.Name, usr.Phone);
这种转换可行吗?
我有一个XML文件,我希望允许最终用户设置字符串的格式。
例如:
<Viewdata>
<Format>{0} - {1}</Format>
<Parm>Name(property of obj being formatted)</Parm>
<Parm>Phone</Parm>
</Viewdata>
在运行时,我需要以某种方式将其转换为 String.Format("{0} - {1}", usr.Name, usr.Phone);
这种转换可行吗?
string fmt = "{0} - {1}"; // get this from your XML somehow
string name = "Chris";
string phone = "1234567";
string name_with_phone = String.Format(fmt, name, phone);
请注意,因为您的最终用户可能会干扰程序,请小心处理。不要忘记FormatException
。
String.Format(fmt, usr.Name, usr.Phone)
。 - Bart Friederichs{name} - {phone}
并记录哪些属性可以接受。然后使用字符串替换来创建格式字符串。这也可以保护你免受用户进行像{0:-10000000000000000000000000}
这样的操作。 - Bart FriederichsDump()
可以用控制台输出代替。void Main()
{
XElement root = XElement.Parse(
@"<Viewdata>
<Format>{0} | {1}</Format>
<Parm>Name</Parm>
<Parm>Phone</Parm>
</Viewdata>");
var formatter = root.Descendants("Format").FirstOrDefault().Value;
var parms = root.Descendants("Parm").Select(x => x.Value).ToArray();
Person person = new Person { Name = "Jack", Phone = "(123)456-7890" };
string formatted = MagicFormatter<Person>(person, formatter, parms);
formatted.Dump();
/// OUTPUT ///
/// Jack | (123)456-7890
}
public string MagicFormatter<T>(T theobj, string formatter, params string[] propertyNames)
{
for (var index = 0; index < propertyNames.Length; index++)
{
PropertyInfo property = typeof(T).GetProperty(propertyNames[index]);
propertyNames[index] = (string)property.GetValue(theobj);
}
return string.Format(formatter, propertyNames);
}
public class Person
{
public string Name { get; set; }
public string Phone { get; set; }
}
您可以使用System.Linq.Dynamic,并使整个格式命令可编辑:
class Person
{
public string Name;
public string Phone;
public Person(string n, string p)
{
Name = n;
Phone = p;
}
}
static void TestDynamicLinq()
{
foreach (var x in new Person[] { new Person("Joe", "123") }.AsQueryable().Select("string.Format(\"{0} - {1}\", it.Name, it.Phone)"))
Console.WriteLine(x);
}
XElement root = XElement.Parse (
@"<Viewdata>
<Format>{0} - {1}</Format>
<Parm>damith</Parm>
<Parm>071444444</Parm>
</Viewdata>");
var format =root.Descendants("Format").FirstOrDefault().Value;
var result = string.Format(format, root.Descendants("Parm")
.Select(x=>x.Value).ToArray());
你可以使用参数名称来指定格式字符串:
<Viewdata>
<Format>{Name} - {Phone}</Format>
</Viewdata>
http://www.codeproject.com/Articles/622309/Extended-string-Format
你可以完成这项工作。
简短的回答是:是的,但这取决于您格式选项的种类,难度会有所不同。
如果您有一些格式化字符串可以接受5个参数,而另一些只能接受3个参数,那么您需要考虑这一点。
我建议使用解析XML获取参数,并将它们存储到对象数组中,以便传递给String.Format函数。