名为String.Format,有可能吗?

而不是使用{0} {1}等我想改用{title} 。 然后以某种方式填充该数据(下面我使用了一个Dictionary )。 此代码无效并引发exception。 我想知道我是否能做类似于我想要的事情。 使用{0 .. N}不是问题。 我只是好奇而已。

 Dictionary d = new Dictionary(); d["a"] = "he"; d["ba"] = "llo"; d["lol"] = "world"; string a = string.Format("{a}{ba}{lol}", d); 

不,但这种扩展方法会做到这一点

 static string FormatFromDictionary(this string formatString, Dictionary ValueDict) { int i = 0; StringBuilder newFormatString = new StringBuilder(formatString); Dictionary keyToInt = new Dictionary(); foreach (var tuple in ValueDict) { newFormatString = newFormatString.Replace("{" + tuple.Key + "}", "{" + i.ToString() + "}"); keyToInt.Add(tuple.Key, i); i++; } return String.Format(newFormatString.ToString(), ValueDict.OrderBy(x => keyToInt[x.Key]).Select(x => x.Value).ToArray()); } 

现在可能了

使用C#6.0的Interpolated Strings ,您可以这样做:

 string name = "John"; string message = $"Hi {name}!"; //"Hi John!" 

检查一下,它支持格式化:

  public static string StringFormat(string format, IDictionary values) { var matches = Regex.Matches(format, @"\{(.+?)\}"); List words = (from Match matche in matches select matche.Groups[1].Value).ToList(); return words.Aggregate( format, (current, key) => { int colonIndex = key.IndexOf(':'); return current.Replace( "{" + key + "}", colonIndex > 0 ? string.Format("{0:" + key.Substring(colonIndex + 1) + "}", values[key.Substring(0, colonIndex)]) : values[key].ToString()); }); } 

如何使用:

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

你可以实现自己的:

 public static string StringFormat(string format, IDictionary values) { foreach(var p in values) format = format.Replace("{" + p.Key + "}", p.Value); return format; } 

Phil Haack在他的博客上讨论了几种方法: http : //haacked.com/archive/2009/01/14/named-formats-redux.aspx 。 我在两个没有投诉的项目中使用了“Hanselformat”版本。

 static public class StringFormat { static private char[] separator = new char[] { ':' }; static private Regex findParameters = new Regex( "\\{(?.*?)\\}", RegexOptions.Compiled | RegexOptions.Singleline); static string FormatNamed( this string format, Dictionary args) { return findParameters.Replace( format, delegate(Match match) { string[] param = match.Groups["param"].Value.Split(separator, 2); object value; if (!args.TryGetValue(param[0], out value)) value = match.Value; if ((param.Length == 2) && (param[1].Length != 0)) return string.Format( CultureInfo.CurrentCulture, "{0:" + param[1] + "}", value); else return value.ToString(); }); } } 

比其他扩展方法更复杂,但是这也应该允许在它们上使用非字符串值和格式化模式,所以在您的原始示例中:

 Dictionary d = new Dictionary(); d["a"] = DateTime.Now; string a = string.FormatNamed("{a:yyyyMMdd-HHmmss}", d); 

也会工作……

自C#6发布以来,您就可以使用字符串插值function

解决您问题的代码:

 string a = $"{d["a"]}{d["ba"]}{d["lol"]}"; 

这是一个很好的解决方案,在格式化电子邮件时非常有用: http : //www.c-sharpcorner.com/UploadFile/e4ff85/string-replacement-with-named-string-placeholders/

编辑:

 public static class StringExtension { public static string Format( this string str, params Expression>[] args) { var parameters = args.ToDictionary( e=>string.Format("{{{0}}}",e.Parameters[0].Name), e=>e.Compile()(e.Parameters[0].Name)); var sb = new StringBuilder(str); foreach(var kv in parameters) { sb.Replace( kv.Key, kv.Value != null ? kv.Value.ToString() : ""); } return sb.ToString(); } } 

用法示例:

 public string PopulateString(string emailBody) { User person = _db.GetCurrentUser(); string firstName = person.FirstName; // Peter string lastName = person.LastName; // Pan return StringExtension.Format(emailBody.Format( firstname => firstName, lastname => lastName )); } 

(你的Dictionary + foreach + string.Replace)包含在子例程或扩展方法中?

显然没有优化,但……