是否可以在不使用连接符的情况下将 C# 变量包含在字符串变量中?

发布于 2024-11-01 01:05:55 字数 1168 浏览 13 评论 0原文

.NET 3.5 C# 是否允许我们在字符串变量中包含变量,而无需使用 + 连接符(或 string.Format())。

例如(在伪中,我使用 $ 符号来指定变量):

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

输出:

日期为 2011 年 4 月 12 日上午 11:56:39

编辑

由于少数回复建议使用 string.Format(),我只能假设我原来的帖子不清楚,当我提到“...(或 string.Format(),就此而言)”。需要明确的是,我很了解 string.Format() 方法。然而,在我正在从事的特定项目中, string.Format() 对我没有帮助(它实际上比 + 连接器更糟糕)。

另外,我推断你们大多数/所有人都想知道我的问题背后的动机是什么(我想如果我按原样阅读我的问题,我也会有同样的感觉)。

如果您对此感到好奇,请简单了解一下:

我正在创建一个在 Windows CE 设备上运行的 Web 应用程序。由于 Web 服务器的工作方式,我在字符串变量中创建整个网页内容(css、js、html 等)。例如,我的 .cs 托管代码可能具有如下内容:

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>
    ";

}

如您所见,能够指定变量而无需连接,使事情变得更容易 - 特别是当内容大小增加时。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(14

通知家属抬走 2024-11-08 01:05:55

不,不幸的是 C# 不是 PHP。
但好的一面是,C# 不是 PHP。

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

挽你眉间 2024-11-08 01:05:55

差不多了,用一个小扩展方法。

static class StringExtensions
{
    public static string PHPIt<T>(this string s, T values, string prefix = "$")
    {
        var sb = new StringBuilder(s);
        foreach(var p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            sb = sb.Replace(prefix + p.Name, p.GetValue(values, null).ToString());
        }
        return sb.ToString();
    }
}

现在我们可以写:

string foo = "Bar";
int cool = 2;

var result = "This is a string $foo with $cool variables"
             .PHPIt(new { 
                    foo, 
                    cool 
                });

//result == "This is a string Bar with 2 variables"

Almost, with a small extension method.

static class StringExtensions
{
    public static string PHPIt<T>(this string s, T values, string prefix = "$")
    {
        var sb = new StringBuilder(s);
        foreach(var p in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            sb = sb.Replace(prefix + p.Name, p.GetValue(values, null).ToString());
        }
        return sb.ToString();
    }
}

And now we can write:

string foo = "Bar";
int cool = 2;

var result = "This is a string $foo with $cool variables"
             .PHPIt(new { 
                    foo, 
                    cool 
                });

//result == "This is a string Bar with 2 variables"
暮光沉寂 2024-11-08 01:05:55

不,事实并非如此。有很多方法可以解决这个问题,但它们违背了目的。对于你的例子来说最简单的事情是

Console.WriteLine("The date is {0}", DateTime.Now);

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);
半寸时光 2024-11-08 01:05:55
string output = "the date is $d and time is $t";
output = output.Replace("$t", t).Replace("$d", d);  //and so on
string output = "the date is $d and time is $t";
output = output.Replace("$t", t).Replace("$d", d);  //and so on
梓梦 2024-11-08 01:05:55

基于@JesperPalm的出色回答,我发现了另一个有趣的解决方案,它让您可以使用与普通 string.Format 方法类似的语法:

public static class StringExtensions
{
    public static string Replace<T>(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);
    }
}

这使您可以添加常用的格式:

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.

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<T>(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.
因为看清所以看轻 2024-11-08 01:05:55

简短的答案是:不!

The short and simple answer is: No!

但可醉心 2024-11-08 01:05:55
string.Format("The date is {0}", DateTime.Now.ToString())
string.Format("The date is {0}", DateTime.Now.ToString())
可是我不能没有你 2024-11-08 01:05:55

不,但是您可以在字符串实例上创建一个扩展方法来缩短输入时间。

string s = "The date is {0}".Format(d);

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);
落叶缤纷 2024-11-08 01:05:55

string.Format(以及类似的格式化函数,例如 StringBuilder.AppendFormat)在灵活性、编码实践和(通常)性能方面是实现此目的的最佳方法

string s = string.Format("The date is {0}", d);

:还可以指定 DateTime 的显示格式,以及在字符串中插入多个对象。查看MSDN 上有关 string.Format 方法的页面

某些类型还重载了其 ToString 方法,允许您指定格式字符串。您还可以为 string 创建一个扩展方法,允许您指定格式和/或解析语法,如下所示。

string.Format (and similar formatting functions such as StringBuilder.AppendFormat) are the best way to do this in terms of flexibility, coding practice, and (usually) performance:

string s = string.Format("The date is {0}", d);

You can also specify the display format of your DateTime, as well as inserting more than one object into the string. Check out MSDN's page on the string.Format method.

Certain types also have overloads to their ToString methods which allow you to specify a format string. You could also create an extension method for string that allows you to specify a format and/or parse syntax like this.

千鲤 2024-11-08 01:05:55

如果您只是想避免不可变字符串的串联,那么您正在寻找的是 StringBuilder.

用法:

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();

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();
红颜悴 2024-11-08 01:05:55

C# 6.0 开始,您可以编写字符串 "The title is \{title}" ,它正是您所需要的。

Since C# 6.0 you can write string "The title is \{title}" which does exactly what you need.

甜尕妞 2024-11-08 01:05:55

您可以使用 C# 文档中提到的类似内容。
字符串插值

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

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

string name = "Horace";
int age = 34;
Console.WriteLine(
quot;He asked, \"Is your name {name}?\", but didn't wait for a reply :-{{");
Console.WriteLine(
quot;{name} is {age} year{(age == 1 ? "" : "s")} old.");
南街女流氓 2024-11-08 01:05:55

或组合:

Console.WriteLine("The date is {0}", DateTime.Now);

额外信息(响应 BrandonZeider):

是的,这对于人们认识到字符串转换是自动完成的很重要。手动添加 ToString 已被破坏,例如:

string value = null;
Console.WriteLine("The value is '{0}'", value); // OK
Console.WriteLine("The value is '{0}'", value.ToString()); // FAILURE

此外,一旦您意识到字符串化不等于使用 .ToString(),这就变得不那么简单了。您可以拥有格式说明符,甚至自定义格式格式提供程序...教人们利用 String.Format 而不是手动执行它非常有趣。

Or combined:

Console.WriteLine("The date is {0}", DateTime.Now);

Extra info (in response to BrandonZeider):

Yep, it is kind-a important for people to realize that string conversion is automatically done. Manually adding ToString is broken, e.g.:

string value = null;
Console.WriteLine("The value is '{0}'", value); // OK
Console.WriteLine("The value is '{0}'", value.ToString()); // FAILURE

Also, this becomes a lot less trivial once you realize that the stringification is not equivalent to using .ToString(). You can have format specifiers, and even custom format format providers... It is interesting enough to teach people to leverage String.Format instead of doing it manually.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文