155

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}", ...);

変数名を使用してこれを実行できると便利ですが、辞書も使用できます。

4

18 に答える 18

129

これを処理するための組み込みの方法はありません。

これが1つの方法です

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

ここに別のものがあります

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

Phil Haackによる、上記の2つに部分的に基づいた3番目の改善された方法

于 2008-10-01T18:49:49.443 に答える
45

ここにブログに投稿したばかりの実装があります:http://haacked.com/archive/2009/01/04/fun-with-named-formats-string-parsing-and-edge-cases.aspx

これは、これらの他の実装が中括弧のエスケープに関して持ついくつかの問題に対処します。投稿には詳細があります。DataBinder.Evalも実行しますが、それでも非常に高速です。

于 2009-01-05T04:32:05.320 に答える
39

次のような匿名タイプを使用することもできます。

    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" })
于 2010-11-02T11:21:19.983 に答える
14

箱から出してこれを行う方法はないようです。ただし、 for値IFormatProviderにリンクする独自の実装は実行可能に見えます。IDictionary

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ため、派手なテキストの書式設定を同時に使用することはできないということです。

于 2008-10-01T19:01:41.753 に答える
9

フレームワーク自体はこれを行う方法を提供していませんが、ScottHanselmanによるこの投稿を見ることができます。使用例:

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 });
于 2008-10-01T19:22:08.740 に答える
7

https://stackoverflow.com/questions/271398?page=2#358259を参照してください

リンク先の拡張機能を使用すると、次のように記述できます。

var str = "{foo} {bar} {baz}".Format(foo=>"foo", bar=>2, baz=>new object());

そして、あなたは得るでしょう"foo 2 System.Object」。

于 2009-01-05T15:38:33.010 に答える
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);
}

Dictionary<string, string> の .Keys コレクションを反復することでそれを行うこともできますが、List<KeyValuePair<string, string>> を使用することで、List の .ForEach() メソッドを利用して元に戻すことができます。ワンライナー:

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

ラムダはさらに単純ですが、私はまだ .Net 2.0 を使用しています。また、.Net の文字列は不変であるため、繰り返し使用すると .Replace() のパフォーマンスが優れていないことにも注意してください。また、これMyStringにはデリゲートがアクセスできるように変数を定義する必要があるため、まだ完全ではありません。

于 2008-10-01T18:32:36.550 に答える
3

私のオープン ソース ライブラリであるRegextraは、(とりわけ) 名前付き書式をサポートしています。現在、.NET 4.0+ を対象としており、NuGetで利用できます。それについての紹介ブログ投稿もあります: Regextra: Helping you reduce your (problems){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 を確認してください。

于 2014-04-19T17:37:48.753 に答える
2
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}

于 2011-05-04T06:56:44.703 に答える
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));

他のソリューションと比較して、パフォーマンスはかなり良好です。

于 2011-09-22T05:53:17.297 に答える
1

これが可能になるとは思えません。最初に頭に浮かぶのは、ローカル変数名にどのようにアクセスするかです。

ただし、これを行うためにLINQ式とLambda式を使用する賢い方法があるかもしれません。

于 2008-10-01T18:33:37.953 に答える
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);

出力: 2012 年 2 月 27 日

于 2012-02-26T23:50:11.840 に答える
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;
        }


    }

}
于 2011-01-29T18:51:11.760 に答える
0

これを実装したのは、String.Format の機能を複製する単純なクラスです (クラスを使用する場合を除く)。ディクショナリまたは型のいずれかを使用してフィールドを定義できます。

https://github.com/SergueiFedorov/NamedFormatString

C# 6.0 では、この機能が言語仕様に直接追加されているNamedFormatStringため、下位互換性のために追加されています。

于 2015-05-14T21:06:47.200 に答える
0

受け入れられた回答はいくつかの良い例を示していますが、.Inject と一部の Haack の例はエスケープを処理しません。また、多くは Regex (遅い)、または .NET Core やその他の環境では利用できない DataBinder.Eval に大きく依存しています。

そのことを念頭に置いて、文字をストリーミングし、文字ごとに出力に書き込む単純なステート マシン ベースのパーサーを作成しました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 の主要な状態に要約されます。ステート マシンがブラケットの外側にあり、同様にブラケットの内側にある場合、次の文字は開き括弧、エスケープされた開き括弧、閉じ括弧、エスケープされた閉じ括弧、もしくは普通のキャラ。これらの各条件は、ループが進行するにつれて個別に処理され、 outputStringBufferまたは keyに文字が追加されますStringBuffer。パラメータがクローズされると、キーの値をStringBuffer使用してディクショナリでパラメータの値が検索され、出力にプッシュされますStringBuffer。最後に、出力の値StringBufferが返されます。

于 2016-02-23T03:08:16.933 に答える
-6
string language = "Python";
int numquotes = 2;
string output = language + " has "+ numquotes + " language types.";

編集:私が言うべきだったのは、「いいえ、あなたがやりたいことがC#でサポートされているとは思わない。これはあなたが得ようとしていることと同じくらい近い」ということでした。

于 2008-10-01T18:42:34.827 に答える