C#中的命名字符串格式


156

有什么方法可以通过名称而不是C#中的位置来格式化字符串?

在python中,我可以执行类似以下示例的操作(从这里无耻地被盗):

>>> print '%(language)s has %(#)03d quote types.' % \
      {'language': "Python", "#": 2}
Python has 002 quote types.

在C#中有什么方法可以做到这一点?例如说:

String.Format("{some_variable}: {some_other_variable}", ...);

能够使用变量名来做到这一点会很好,但是字典也是可以接受的。


我也从Ruby中缺少此功能。
JesperE

我认为您的示例过于简单,导致人们给您无用的答案。也许在字符串中多次使用一个变量将更具示范性。

实际上,SPECIFIC的混淆是String.Format的使用。这很适合我的答案,因为它们不是面向变量的,但对于String.Format而言是准确的,因此无济于事。
约翰·鲁迪

1
显然,对String.Format的调用是一个人为的示例。除非您当然不知道不可能用省略号调用String.Format。问题是我没有说过我希望格式化是通过命名参数而不是位置进行的,该方法已经解决了。
杰森·贝克

仅供参考:提交给MS Connect的用户语音,要求将此作为框架的标准功能。任何有兴趣,请给予好评:visualstudio.uservoice.com/forums/121579-visual-studio/...
JohnLBevan

Answers:


130

没有内置方法可以处理此问题。

这是一种方法

string myString = "{foo} is {bar} and {yadi} is {yada}".Inject(o);

这是另一个

Status.Text = "{UserName} last logged in at {LastLoginDate}".FormatWith(user);

部分基于以上两个方面的第三种改进方法,来自Phil Haack


11
我对使用FormatWith()非常满意,但想指出我最近遇到的一个问题。该实现依赖于System.Web.UI中的DataBinder,SQL CLR中不支持。Inject(o)不依赖于数据绑定器,这使其可用于SQL CLR对象中的多令牌替换。
EBarr

1
也许您可以更新答案的第一句话。字符串插值在C#和VB中存在了几个月(最终...)。您的答案在顶部,因此如果您可以将读者链接到一些更新的.NET资源,则可能对读者有用。
miroxlav

1
@miroxlav并不是真的一样。您不能在周围传递插值字符串:stackoverflow.com/q/31987232/213725
DixonD

@DixonD –您绝对正确,但这不是他们的目的。在您链接的问答中,OP试图在变量名存在之前先对其进行引用。这不是一个好主意,但是如果有人坚持这样做,他可以构建专门的解析器。但是我不会把它与一般的字符串插值概念搞混。
miroxlav

44

我有一个刚刚发布到我的博客的实现:http : //haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx

它通过大括号转义解决了其他实现所遇到的一些问题。该帖子有详细信息。它也执行DataBinder.Eval的事情,但是仍然非常快。


3
该文章404中可供下载的代码。我也很想看看。
quentin-starin's

2
@qes:在评论中发布了更新的链接:code.haacked.com/util/NamedStringFormatSolution.zip
Der Hochstapler,2012年

3
@OliverSalzburg:很长时间以来,我一直在使用SmartFormat满足我的所有格式化需求,喜欢它。github.com/scottrippey/SmartFormat
quentin-

@qes:您介意对此进行写作和回答并展示其工作原理吗?看起来很有趣
Der Hochstapler,2012年

@qes:您绝对应该添加SmartFormat作为答案,因为它非常好并且受到积极支持(2015)。
的Răzvan弗拉菲乌斯熊猫

42

内插字符串已添加到C#6.0和Visual Basic 14中

两者都是通过Visual Studio 2015中新的Roslyn编译器引入的。

  • C#6.0:

    return "\{someVariable} and also \{someOtherVariable}" 要么
    return $"{someVariable} and also {someOtherVariable}"

  • VB 14:

    return $"{someVariable} and also {someOtherVariable}"

值得注意的功能(在Visual Studio 2015 IDE中):

  • 支持语法着色 -字符串中包含的变量突出显示
  • 支持重构 -重命名时,字符串中包含的变量也将重命名
  • 实际上不仅支持变量名,还支持表达式 -例如,不仅{index}可以使用,而且还可以{(index + 1).ToString().Trim()}

请享用!(并在VS中单击“发送微笑”)


2
该问题用.net 3.5标记,因此您的信息有效,但不是替代选择
Douglas Gandini

1
@miroxlav-您对框架版本是正确的。字符串插值只是取决于VS 2015中使用的新的罗斯林编译器
道格拉斯·甘迪尼

2
除非您将格式字符串放入代码本身,否则这也将不起作用。也就是说,如果您的格式字符串来自外部资源(如配置文件或数据库),则它将不起作用。
Craig Brett

40

您还可以使用如下匿名类型:

    public string Format(string input, object p)
    {
        foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(p))
            input = input.Replace("{" + prop.Name + "}", (prop.GetValue(p) ?? "(null)").ToString());

        return input;
    }

当然,如果您还想解析格式,则需要更多代码,但是可以使用以下函数来格式化字符串:

Format("test {first} and {another}", new { first = "something", another = "something else" })

1
对于仍然使用2.0的我们来说是完美的。是的,我知道...。此解决方案简单明了。和它的工作!
布拉德·布鲁斯

14

似乎没有开箱即用的方法。不过,实现自己IFormatProviderIDictionaryfor值链接似乎可行。

var Stuff = new Dictionary<string, object> {
   { "language", "Python" },
   { "#", 2 }
};
var Formatter = new DictionaryFormatProvider();

// Interpret {0:x} where {0}=IDictionary and "x" is hash key
Console.WriteLine string.Format(Formatter, "{0:language} has {0:#} quote types", Stuff);

输出:

Python有2种报价类型

需要注意的是您不能混合使用FormatProviders,因此不能同时使用精美的文本格式。


1
+1是概述,恕我直言,这是最好的概念方法,可在mo.notono.us/2008/07/c-stringinject-format-strings-by-key.html上很好地实现-其他文章也包括此内容,但它们提出基于反射的方法,恕我直言,这是非常邪恶的
Adam Ralph

9

框架本身没有提供执行此操作的方法,但是您可以阅读Scott Hanselman的这篇文章。用法示例:

Person p = new Person();  
string foo = p.ToString("{Money:C} {LastName}, {ScottName} {BirthDate}");  
Assert.AreEqual("$3.43 Hanselman, {ScottName} 1/22/1974 12:00:00 AM", foo); 

James Newton-King的这段代码与之类似,可用于子属性和索引,

string foo = "Top result for {Name} was {Results[0].Name}".FormatWith(student));

James的代码依赖于System.Web.UI.DataBinder来解析字符串,并且需要引用System.Web,有些人不喜欢在非Web应用程序中这样做。

编辑:哦,如果您没有对象准备好属性,它们可以很好地与匿名类型配合使用:

string name = ...;
DateTime date = ...;
string foo = "{Name} - {Birthday}".FormatWith(new { Name = name, Birthday = date });


4

我认为最接近的是索引格式:

String.Format("{0} has {1} quote types.", "C#", "1");

还有一个String.Replace(),如果您愿意分多个步骤进行操作,并坚信您不会在字符串的其他任何地方找到“变量”:

string MyString = "{language} has {n} quote types.";
MyString = MyString.Replace("{language}", "C#").Replace("{n}", "1");

将其扩展为使用列表:

List<KeyValuePair<string, string>> replacements = GetFormatDictionary();  
foreach (KeyValuePair<string, string> item in replacements)
{
    MyString = MyString.Replace(item.Key, item.Value);
}

您也可以通过循环访问它的.Keys集合来使用Dictionary <string,string>来做到这一点,但是通过使用List <KeyValuePair <string,string >>,我们可以利用List的.ForEach()方法并将其压缩回单线:

replacements.ForEach(delegate(KeyValuePair<string,string>) item) { MyString = MyString.Replace(item.Key, item.Value);});

Lambda甚至会更简单,但是我仍然使用.Net 2.0。还要注意,由于.Net中的字符串是不可变的,因此当迭代使用.Replace()时性能并不佳。另外,这要求MyString以这样的方式定义变量,使得委托可以访问该变量,因此它还不是完美的。


好吧,这不是最漂亮的解决方案,但这是我现在要使用的解决方案。我唯一做的不同的事情是使用StringBuilder而不是字符串,这样我就不会继续制作新的字符串。
杰森·贝克

3

我的开源库Regextra支持命名格式(除其他外)。它当前面向.NET 4.0+,并且在NuGet上可用。我也有一个介绍性的博客文章:Regextra:帮助您减少(问题){2}

命名格式位支持:

  • 基本格式
  • 嵌套属性格式
  • 字典格式
  • 转义分隔符
  • 标准/自定义/ IFormatProvider字符串格式

例:

var order = new
{
    Description = "Widget",
    OrderDate = DateTime.Now,
    Details = new
    {
        UnitPrice = 1500
    }
};

string template = "We just shipped your order of '{Description}', placed on {OrderDate:d}. Your {{credit}} card will be billed {Details.UnitPrice:C}.";

string result = Template.Format(template, order);
// or use the extension: template.FormatTemplate(order);

结果:

我们刚刚于2014年2月28日发送了您的“小部件”订单。您的{credit}卡的费用为$ 1,500.00。

查看该项目的GitHub链接(上方)和Wiki,以获得其他示例。


哇,这看起来很棒,特别是在处理一些较困难的格式示例时。
尼古拉斯·彼得森

2

检查这一:

public static string StringFormat(string format, object source)
{
    var matches = Regex.Matches(format, @"\{(.+?)\}");
    List<string> keys = (from Match matche in matches select matche.Groups[1].Value).ToList();

    return keys.Aggregate(
        format,
        (current, key) =>
        {
            int colonIndex = key.IndexOf(':');
            return current.Replace(
                "{" + key + "}",
                colonIndex > 0
                    ? DataBinder.Eval(source, key.Substring(0, colonIndex), "{0:" + key.Substring(colonIndex + 1) + "}")
                    : DataBinder.Eval(source, key).ToString());
        });
}

样品:

string format = "{foo} is a {bar} is a {baz} is a {qux:#.#} is a really big {fizzle}";
var o = new { foo = 123, bar = true, baz = "this is a test", qux = 123.45, fizzle = DateTime.Now };
Console.WriteLine(StringFormat(format, o));

与其他解决方案相比,性能还可以。


1

我怀疑这是否可能。首先想到的是如何访问局部变量名?

但是,可能有一些使用LINQ和Lambda表达式的巧妙方法。


@leppie:+1,如果您可以给我一些LINQ + Lambda来做到这一点; D(可以通过+1获得相关答案)
user7116

我也希望看到它!也许我会接受挑战!
嬉皮

我认为使用变量名是不可能的,但是如果我弄错了,那就把它放在那儿。:)也没有任何方法可以使用字典吗?
杰森·贝克

我尝试过,并在某个地方放了一点,但我觉得它太丑陋且难以使用。看起来像是:string s = format(f => f(“ {hello} {world}”,hello,world));
嬉皮

1

这是我前一段时间做的。它使用带有单个参数的Format方法扩展String。不错的是,如果您提供一个简单的参数(例如int),它将使用标准的string.Format格式,但是如果您使用类似匿名类型的名称,它也会起作用。

用法示例:

"The {Name} family has {Children} children".Format(new { Children = 4, Name = "Smith" })

会导致“史密斯一家有4个孩子”。

它不会疯狂​​绑定诸如数组和索引器之类的东西。但这是超级简单和高性能。

    public static class AdvancedFormatString
{

    /// <summary>
    /// An advanced version of string.Format.  If you pass a primitive object (string, int, etc), it acts like the regular string.Format.  If you pass an anonmymous type, you can name the paramters by property name.
    /// </summary>
    /// <param name="formatString"></param>
    /// <param name="arg"></param>
    /// <returns></returns>
    /// <example>
    /// "The {Name} family has {Children} children".Format(new { Children = 4, Name = "Smith" })
    /// 
    /// results in 
    /// "This Smith family has 4 children
    /// </example>
    public static string Format(this string formatString, object arg, IFormatProvider format = null)
    {
        if (arg == null)
            return formatString;

        var type = arg.GetType();
        if (Type.GetTypeCode(type) != TypeCode.Object || type.IsPrimitive)
            return string.Format(format, formatString, arg);

        var properties = TypeDescriptor.GetProperties(arg);
        return formatString.Format((property) =>
            {
                var value = properties[property].GetValue(arg);
                return Convert.ToString(value, format);
            });
    }


    public static string Format(this string formatString, Func<string, string> formatFragmentHandler)
    {
        if (string.IsNullOrEmpty(formatString))
            return formatString;
        Fragment[] fragments = GetParsedFragments(formatString);
        if (fragments == null || fragments.Length == 0)
            return formatString;

        return string.Join(string.Empty, fragments.Select(fragment =>
            {
                if (fragment.Type == FragmentType.Literal)
                    return fragment.Value;
                else
                    return formatFragmentHandler(fragment.Value);
            }).ToArray());
    }


    private static Fragment[] GetParsedFragments(string formatString)
    {
        Fragment[] fragments;
        if ( parsedStrings.TryGetValue(formatString, out fragments) )
        {
            return fragments;
        }
        lock (parsedStringsLock)
        {
            if ( !parsedStrings.TryGetValue(formatString, out fragments) )
            {
                fragments = Parse(formatString);
                parsedStrings.Add(formatString, fragments);
            }
        }
        return fragments;
    }

    private static Object parsedStringsLock = new Object();
    private static Dictionary<string,Fragment[]> parsedStrings = new Dictionary<string,Fragment[]>(StringComparer.Ordinal);

    const char OpeningDelimiter = '{';
    const char ClosingDelimiter = '}';

    /// <summary>
    /// Parses the given format string into a list of fragments.
    /// </summary>
    /// <param name="format"></param>
    /// <returns></returns>
    static Fragment[] Parse(string format)
    {
        int lastCharIndex = format.Length - 1;
        int currFragEndIndex;
        Fragment currFrag = ParseFragment(format, 0, out currFragEndIndex);

        if (currFragEndIndex == lastCharIndex)
        {
            return new Fragment[] { currFrag };
        }

        List<Fragment> fragments = new List<Fragment>();
        while (true)
        {
            fragments.Add(currFrag);
            if (currFragEndIndex == lastCharIndex)
            {
                break;
            }
            currFrag = ParseFragment(format, currFragEndIndex + 1, out currFragEndIndex);
        }
        return fragments.ToArray();

    }

    /// <summary>
    /// Finds the next delimiter from the starting index.
    /// </summary>
    static Fragment ParseFragment(string format, int startIndex, out int fragmentEndIndex)
    {
        bool foundEscapedDelimiter = false;
        FragmentType type = FragmentType.Literal;

        int numChars = format.Length;
        for (int i = startIndex; i < numChars; i++)
        {
            char currChar = format[i];
            bool isOpenBrace = currChar == OpeningDelimiter;
            bool isCloseBrace = isOpenBrace ? false : currChar == ClosingDelimiter;

            if (!isOpenBrace && !isCloseBrace)
            {
                continue;
            }
            else if (i < (numChars - 1) && format[i + 1] == currChar)
            {//{{ or }}
                i++;
                foundEscapedDelimiter = true;
            }
            else if (isOpenBrace)
            {
                if (i == startIndex)
                {
                    type = FragmentType.FormatItem;
                }
                else
                {

                    if (type == FragmentType.FormatItem)
                        throw new FormatException("Two consequtive unescaped { format item openers were found.  Either close the first or escape any literals with another {.");

                    //curr character is the opening of a new format item.  so we close this literal out
                    string literal = format.Substring(startIndex, i - startIndex);
                    if (foundEscapedDelimiter)
                        literal = ReplaceEscapes(literal);

                    fragmentEndIndex = i - 1;
                    return new Fragment(FragmentType.Literal, literal);
                }
            }
            else
            {//close bracket
                if (i == startIndex || type == FragmentType.Literal)
                    throw new FormatException("A } closing brace existed without an opening { brace.");

                string formatItem = format.Substring(startIndex + 1, i - startIndex - 1);
                if (foundEscapedDelimiter)
                    formatItem = ReplaceEscapes(formatItem);//a format item with a { or } in its name is crazy but it could be done
                fragmentEndIndex = i;
                return new Fragment(FragmentType.FormatItem, formatItem);
            }
        }

        if (type == FragmentType.FormatItem)
            throw new FormatException("A format item was opened with { but was never closed.");

        fragmentEndIndex = numChars - 1;
        string literalValue = format.Substring(startIndex);
        if (foundEscapedDelimiter)
            literalValue = ReplaceEscapes(literalValue);

        return new Fragment(FragmentType.Literal, literalValue);

    }

    /// <summary>
    /// Replaces escaped brackets, turning '{{' and '}}' into '{' and '}', respectively.
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    static string ReplaceEscapes(string value)
    {
        return value.Replace("{{", "{").Replace("}}", "}");
    }

    private enum FragmentType
    {
        Literal,
        FormatItem
    }

    private class Fragment
    {

        public Fragment(FragmentType type, string value)
        {
            Type = type;
            Value = value;
        }

        public FragmentType Type
        {
            get;
            private set;
        }

        /// <summary>
        /// The literal value, or the name of the fragment, depending on fragment type.
        /// </summary>
        public string Value
        {
            get;
            private set;
        }


    }

}

1
private static Regex s_NamedFormatRegex = new Regex(@"\{(?!\{)(?<key>[\w]+)(:(?<fmt>(\{\{|\}\}|[^\{\}])*)?)?\}", RegexOptions.Compiled);

public static StringBuilder AppendNamedFormat(this StringBuilder builder,IFormatProvider provider, string format, IDictionary<string, object> args)
{
    if (builder == null) throw new ArgumentNullException("builder");
    var str = s_NamedFormatRegex.Replace(format, (mt) => {
        string key = mt.Groups["key"].Value;
        string fmt = mt.Groups["fmt"].Value;
        object value = null;
        if (args.TryGetValue(key,out value)) {
            return string.Format(provider, "{0:" + fmt + "}", value);
        } else {
            return mt.Value;
        }
    });
    builder.Append(str);
    return builder;
}

public static StringBuilder AppendNamedFormat(this StringBuilder builder, string format, IDictionary<string, object> args)
{
    if (builder == null) throw new ArgumentNullException("builder");
    return builder.AppendNamedFormat(null, format, args);
}

例:

var builder = new StringBuilder();
builder.AppendNamedFormat(
@"你好,{Name},今天是{Date:yyyy/MM/dd}, 这是你第{LoginTimes}次登录,积分{Score:{{ 0.00 }}}",
new Dictionary<string, object>() { 
    { "Name", "wayjet" },
    { "LoginTimes",18 },
    { "Score", 100.4 },
    { "Date",DateTime.Now }
});

输出:你好,wayjet,今天是2011-05-04,这是你第18次登录,积分{100.40}


1

这是任何对象的简单方法:

    using System.Text.RegularExpressions;
    using System.ComponentModel;

    public static string StringWithFormat(string format, object args)
    {
        Regex r = new Regex(@"\{([A-Za-z0-9_]+)\}");

        MatchCollection m = r.Matches(format);

        var properties = TypeDescriptor.GetProperties(args);

        foreach (Match item in m)
        {
            try
            {
                string propertyName = item.Groups[1].Value;
                format = format.Replace(item.Value, properties[propertyName].GetValue(args).ToString());
            }
            catch
            {
                throw new FormatException("The format string is not valid");
            }
        }

        return format;
    }

以及如何使用它:

 DateTime date = DateTime.Now;
 string dateString = StringWithFormat("{Month}/{Day}/{Year}", date);

输出:2/27/2012



0

我以与现有解决方案稍有不同的方式解决了这个问题。它执行命名项替换的核心(而不是某些项完成的反射位)。这是非常快速和简单的...这是我的解决方案:

/// <summary>
/// Formats a string with named format items given a template dictionary of the items values to use.
/// </summary>
public class StringTemplateFormatter
{
    private readonly IFormatProvider _formatProvider;

    /// <summary>
    /// Constructs the formatter with the specified <see cref="IFormatProvider"/>.
    /// This is defaulted to <see cref="CultureInfo.CurrentCulture">CultureInfo.CurrentCulture</see> if none is provided.
    /// </summary>
    /// <param name="formatProvider"></param>
    public StringTemplateFormatter(IFormatProvider formatProvider = null)
    {
        _formatProvider = formatProvider ?? CultureInfo.CurrentCulture;
    }

    /// <summary>
    /// Formats a string with named format items given a template dictionary of the items values to use.
    /// </summary>
    /// <param name="text">The text template</param>
    /// <param name="templateValues">The named values to use as replacements in the formatted string.</param>
    /// <returns>The resultant text string with the template values replaced.</returns>
    public string FormatTemplate(string text, Dictionary<string, object> templateValues)
    {
        var formattableString = text;
        var values = new List<object>();
        foreach (KeyValuePair<string, object> value in templateValues)
        {
            var index = values.Count;
            formattableString = ReplaceFormattableItem(formattableString, value.Key, index);
            values.Add(value.Value);
        }
        return String.Format(_formatProvider, formattableString, values.ToArray());
    }

    /// <summary>
    /// Convert named string template item to numbered string template item that can be accepted by <see cref="string.Format(string,object[])">String.Format</see>
    /// </summary>
    /// <param name="formattableString">The string containing the named format item</param>
    /// <param name="itemName">The name of the format item</param>
    /// <param name="index">The index to use for the item value</param>
    /// <returns>The formattable string with the named item substituted with the numbered format item.</returns>
    private static string ReplaceFormattableItem(string formattableString, string itemName, int index)
    {
        return formattableString
            .Replace("{" + itemName + "}", "{" + index + "}")
            .Replace("{" + itemName + ",", "{" + index + ",")
            .Replace("{" + itemName + ":", "{" + index + ":");
    }
}

它以以下方式使用:

    [Test]
    public void FormatTemplate_GivenANamedGuid_FormattedWithB_ShouldFormatCorrectly()
    {
        // Arrange
        var template = "My guid {MyGuid:B} is awesome!";
        var templateValues = new Dictionary<string, object> { { "MyGuid", new Guid("{A4D2A7F1-421C-4A1D-9CB2-9C2E70B05E19}") } };
        var sut = new StringTemplateFormatter();
        // Act
        var result = sut.FormatTemplate(template, templateValues);
        //Assert
        Assert.That(result, Is.EqualTo("My guid {a4d2a7f1-421c-4a1d-9cb2-9c2e70b05e19} is awesome!"));
    }

希望有人觉得这有用!


0

即使已接受的答案提供了一些很好的示例,.Inject以及一些Haack示例也无法处理转义。许多服务器还严重依赖于Regex(速度较慢)或DataBinder.Eval(在.NET Core和某些其他环境中不可用)。

考虑到这一点,我编写了一个基于状态机的简单解析器,该解析器通过字符流式传输,并StringBuilder逐个字符地写入输出。它被实现为String扩展方法,可以同时使用Dictionary<string, object>object以参数作为输入(使用反射)。

当输入包含不平衡的花括号和/或其他错误时,它将处理无限级别的{{{escaping}}}并引发FormatException

public static class StringExtension {
    /// <summary>
    /// Extension method that replaces keys in a string with the values of matching object properties.
    /// </summary>
    /// <param name="formatString">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>
    /// <param name="injectionObject">The object whose properties should be injected in the string</param>
    /// <returns>A version of the formatString string with keys replaced by (formatted) key values.</returns>
    public static string FormatWith(this string formatString, object injectionObject) {
        return formatString.FormatWith(GetPropertiesDictionary(injectionObject));
    }

    /// <summary>
    /// Extension method that replaces keys in a string with the values of matching dictionary entries.
    /// </summary>
    /// <param name="formatString">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>
    /// <param name="dictionary">An <see cref="IDictionary"/> with keys and values to inject into the string</param>
    /// <returns>A version of the formatString string with dictionary keys replaced by (formatted) key values.</returns>
    public static string FormatWith(this string formatString, IDictionary<string, object> dictionary) {
        char openBraceChar = '{';
        char closeBraceChar = '}';

        return FormatWith(formatString, dictionary, openBraceChar, closeBraceChar);
    }
        /// <summary>
        /// Extension method that replaces keys in a string with the values of matching dictionary entries.
        /// </summary>
        /// <param name="formatString">The format string, containing keys like {foo} and {foo:SomeFormat}.</param>
        /// <param name="dictionary">An <see cref="IDictionary"/> with keys and values to inject into the string</param>
        /// <returns>A version of the formatString string with dictionary keys replaced by (formatted) key values.</returns>
    public static string FormatWith(this string formatString, IDictionary<string, object> dictionary, char openBraceChar, char closeBraceChar) {
        string result = formatString;
        if (dictionary == null || formatString == null)
            return result;

        // start the state machine!

        // ballpark output string as two times the length of the input string for performance (avoids reallocating the buffer as often).
        StringBuilder outputString = new StringBuilder(formatString.Length * 2);
        StringBuilder currentKey = new StringBuilder();

        bool insideBraces = false;

        int index = 0;
        while (index < formatString.Length) {
            if (!insideBraces) {
                // currently not inside a pair of braces in the format string
                if (formatString[index] == openBraceChar) {
                    // check if the brace is escaped
                    if (index < formatString.Length - 1 && formatString[index + 1] == openBraceChar) {
                        // add a brace to the output string
                        outputString.Append(openBraceChar);
                        // skip over braces
                        index += 2;
                        continue;
                    }
                    else {
                        // not an escaped brace, set state to inside brace
                        insideBraces = true;
                        index++;
                        continue;
                    }
                }
                else if (formatString[index] == closeBraceChar) {
                    // handle case where closing brace is encountered outside braces
                    if (index < formatString.Length - 1 && formatString[index + 1] == closeBraceChar) {
                        // this is an escaped closing brace, this is okay
                        // add a closing brace to the output string
                        outputString.Append(closeBraceChar);
                        // skip over braces
                        index += 2;
                        continue;
                    }
                    else {
                        // this is an unescaped closing brace outside of braces.
                        // throw a format exception
                        throw new FormatException($"Unmatched closing brace at position {index}");
                    }
                }
                else {
                    // the character has no special meaning, add it to the output string
                    outputString.Append(formatString[index]);
                    // move onto next character
                    index++;
                    continue;
                }
            }
            else {
                // currently inside a pair of braces in the format string
                // found an opening brace
                if (formatString[index] == openBraceChar) {
                    // check if the brace is escaped
                    if (index < formatString.Length - 1 && formatString[index + 1] == openBraceChar) {
                        // there are escaped braces within the key
                        // this is illegal, throw a format exception
                        throw new FormatException($"Illegal escaped opening braces within a parameter - index: {index}");
                    }
                    else {
                        // not an escaped brace, we have an unexpected opening brace within a pair of braces
                        throw new FormatException($"Unexpected opening brace inside a parameter - index: {index}");
                    }
                }
                else if (formatString[index] == closeBraceChar) {
                    // handle case where closing brace is encountered inside braces
                    // don't attempt to check for escaped braces here - always assume the first brace closes the braces
                    // since we cannot have escaped braces within parameters.

                    // set the state to be outside of any braces
                    insideBraces = false;

                    // jump over brace
                    index++;

                    // at this stage, a key is stored in current key that represents the text between the two braces
                    // do a lookup on this key
                    string key = currentKey.ToString();
                    // clear the stringbuilder for the key
                    currentKey.Clear();

                    object outObject;

                    if (!dictionary.TryGetValue(key, out outObject)) {
                        // the key was not found as a possible replacement, throw exception
                        throw new FormatException($"The parameter \"{key}\" was not present in the lookup dictionary");
                    }

                    // we now have the replacement value, add the value to the output string
                    outputString.Append(outObject);

                    // jump to next state
                    continue;
                } // if }
                else {
                    // character has no special meaning, add it to the current key
                    currentKey.Append(formatString[index]);
                    // move onto next character
                    index++;
                    continue;
                } // else
            } // if inside brace
        } // while

        // after the loop, if all braces were balanced, we should be outside all braces
        // if we're not, the input string was misformatted.
        if (insideBraces) {
            throw new FormatException("The format string ended before the parameter was closed.");
        }

        return outputString.ToString();
    }

    /// <summary>
    /// Creates a Dictionary from an objects properties, with the Key being the property's
    /// name and the Value being the properties value (of type object)
    /// </summary>
    /// <param name="properties">An object who's properties will be used</param>
    /// <returns>A <see cref="Dictionary"/> of property values </returns>
    private static Dictionary<string, object> GetPropertiesDictionary(object properties) {
        Dictionary<string, object> values = null;
        if (properties != null) {
            values = new Dictionary<string, object>();
            PropertyDescriptorCollection props = TypeDescriptor.GetProperties(properties);
            foreach (PropertyDescriptor prop in props) {
                values.Add(prop.Name, prop.GetValue(properties));
            }
        }
        return values;
    }
}

最终,所有逻辑都归结为10种主要状态-例如,当状态机位于括号外部且同样位于括号内部时,下一个字符是一个开放括号,一个逃逸的开放括号,一个封闭括号,一个逃逸的封闭括号,或普通字符。这些条件中的每一个都会随着循环的进行而单独处理,将字符添加到输出StringBuffer或键中StringBuffer。关闭参数后,键StringBuffer的值将用于在字典中查找参数的值,然后将其压入输出StringBuffer。最后,StringBuffer返回输出值。


-6
string language = "Python";
int numquotes = 2;
string output = language + " has "+ numquotes + " language types.";

编辑:我应该说的是,“不,我不相信C#支持您要执行的操作。这与您将要实现的目标非常接近。”


1
我对降票感到好奇。有人想告诉我为什么吗?
凯文(Kevin)

1
因此string.format可以更快地执行此操作4 /千分之一秒。如果要调用此功能,您可能会注意到这种差异。但这至少回答了他的问题,而不仅仅是告诉他按照他已经说过的那样做。
凯文”

4
我没有否决您的意见,但我不会实施此方法,主要是因为好吧,我发现执行许多字符串连接很丑陋。但这是我的个人观点。
杰森·贝克

对此感到奇怪的是,投票如此之多。考虑扩大您的答案,这样当不经常调用串联时,您可以考虑"someString" + someVariable + "someOtherString"提高可读性。本文与您同意。
史蒂文·杰里斯
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.