Is it possible to include a C# variable in a strin

2020-06-12 03:04发布

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 the pseudo, I'm using a $ symbol to specify the variable):

DateTime d = DateTime.Now;
string s = "The date is $d";
Console.WriteLine(s);

Output:

The date is 4/12/2011 11:56:39 AM

Edit

Due to the handful of responses that suggested string.Format(), I can only assume that my original post wasn't clear when I mentioned "...(or string.Format(), for that matter)". To be clear, I'm well aware of the string.Format() method. However, in my specific project that I'm working on, string.Format() doesn't help me (it's actually worse than the + concatenator).

Also, I'm inferring that most/all of you are wondering what the motive behind my question is (I suppose I'd feel the same way if I read my question as is).

If you are one of the curious, here's the short of it:

I'm creating a web app running on a Windows CE device. Due to how the web server works, I create the entire web page content (css, js, html, etc) within a string variable. For example, my .cs managed code might have something like this:

string GetPageData()
    {
    string title = "Hello";
    DateTime date = DateTime.Now;

    string html = @"
    <!DOCTYPE html PUBLIC ...>
    <html>
    <head>
        <title>$title</title>
    </head>
    <body>
    <div>Hello StackO</div>
    <div>The date is $date</div>
    </body>
    </html>
    ";

}

As you can see, having the ability to specify a variable without the need to concatenate, makes things a bit easier - especially when the content increases in size.

13条回答
小情绪 Triste *
3楼-- · 2020-06-12 03:58

No, unfortunately C# is not PHP.
On the bright side though, C# is not PHP.

查看更多
\"骚年 ilove
4楼-- · 2020-06-12 04:00

The short and simple answer is: No!

查看更多
疯言疯语
5楼-- · 2020-06-12 04:02
string output = "the date is $d and time is $t";
output = output.Replace("$t", t).Replace("$d", d);  //and so on
查看更多
Animai°情兽
6楼-- · 2020-06-12 04:03

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);
查看更多
三岁会撩人
7楼-- · 2020-06-12 04:06

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);
查看更多
登录 后发表回答