Is it possible to include a C# variable in a string variable without using a concatenator?

前端 未结 14 1798
遥遥无期
遥遥无期 2021-02-14 07:02

Does .NET 3.5 C# allow us to include a variable within a string variable without having to use the + concatenator (or string.Format(), for that matter).

For example (In

14条回答
  •  不知归路
    2021-02-14 07:30

    Based on the great answer of @JesperPalm I found another interesting solution which let's you use a similar syntax like in the normal string.Format method:

    public static class StringExtensions
    {
        public static string Replace(this string text, T values)
        {
            var sb = new StringBuilder(text);
            var properties = typeof(T)
                .GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .ToArray();
    
            var args = properties
                .Select(p => p.GetValue(values, null))
                .ToArray();
    
            for (var i = 0; i < properties.Length; i++)
            {
                var oldValue = string.Format("{{{0}", properties[i].Name);
                var newValue = string.Format("{{{0}", i);
    
                sb.Replace(oldValue, newValue);
            }
    
            var format = sb.ToString();
    
            return string.Format(format, args);
        }
    }
    

    This gives you the possibility to add the usual formatting:

    var hello = "Good morning";
    var world = "Mr. Doe";
    var s = "{hello} {world}! It is {Now:HH:mm}."
        .Replace(new { hello, world, DateTime.Now });
    
    Console.WriteLine(s); // -> Good morning Mr. Doe! It is 13:54.
    

提交回复
热议问题