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

前端 未结 14 1803
遥遥无期
遥遥无期 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:38

    No, But you can create an extension method on the string instance to make the typing shorter.

    string s = "The date is {0}".Format(d);
    
    0 讨论(0)
  • 2021-02-14 07:40

    No, it doesn't. There are ways around this, but they defeat the purpose. Easiest thing for your example is

    Console.WriteLine("The date is {0}", DateTime.Now);
    
    0 讨论(0)
  • 2021-02-14 07:42

    How about using the T4 templating engine?

    http://visualstudiomagazine.com/articles/2009/05/01/visual-studios-t4-code-generation.aspx

    0 讨论(0)
  • 2021-02-14 07:42

    you can use something like this as mentioned in C# documentation. string interpolation

    string name = "Horace";
    int age = 34;
    Console.WriteLine($"He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
    Console.WriteLine($"{name} is {age} year{(age == 1 ? "" : "s")} old.");
    
    0 讨论(0)
  • 2021-02-14 07:46

    The short and simple answer is: No!

    0 讨论(0)
  • 2021-02-14 07:49

    If you are just trying to avoid concatenation of immutable strings, what you're looking for is StringBuilder.

    Usage:

    string parameterName = "Example";
    int parameterValue = 1;
    Stringbuilder builder = new StringBuilder();
    builder.Append("The output parameter ");
    builder.Append(parameterName);
    builder.Append("'s value is ");
    builder.Append(parameterValue.ToString());
    string totalExample = builder.ToString();
    
    0 讨论(0)
提交回复
热议问题