在运行时设置String.Format

本文关键字:Format String 设置 运行时 | 更新日期: 2023-09-27 18:27:13

我有一个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.Format

当然。格式化字符串就是这样,字符串。

 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

我同意其他海报的说法,他们说你可能不应该这样做,但这并不意味着我们不能从这个有趣的问题中获得乐趣。因此,首先,这个解决方案是半生不熟/粗糙的,但如果有人想构建它,这是一个良好的开端。

我用我喜欢的LinqPad写的,所以Dump()可以用控制台写行代替。

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; }
}
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参数,则需要将其考虑在内。

我将解析params的XML,并将其存储到对象数组中,然后传递给String.Format函数。

您可以使用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);
}