gpt4 book ai didi

c# - const 字符串字段与 "typed"字符串

转载 作者:太空狗 更新时间:2023-10-30 00:32:47 27 4
gpt4 key购买 nike

我有一个像这样的小函数:

void Bar(string s)
{
*/ do somthing with the string here.*/
}

void Foo()
{
Bar("Hello");
}

如果我查看 IL 输出,它会给出以下信息:

.method private hidebysig instance void Foo() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: ldstr "Hello"
L_0006: call instance void TestApp.MainWindow::Bar(string)
L_000b: ret
}

现在我想我应该用 const string 字段替换它。

const string str= "Hello";
void Foo()
{
Bar(str);
}

翻译TO THE EXACT SAME IL 片段。

现在我的问题是使用哪一个?

Foo("Hello");Foo(cHello);

感谢您的帮助!

------------编辑----------------
更具体地说,我将其用于日志记录目的以向消息添加前缀:而且它只会在代码中出现一次!

所以它看起来更像这样:

void LogDebug(string msg)
{
Log("[DEBUG]", msg)
}
void Log(string pre, string msg)
{
// generates an output in form of
// pre + msg
}

:)

最佳答案

答案应该很明显:因为 IL 是相同的,所以根据纯粹的源代码考虑使用任何最有效的。

一般来说,这意味着要使用 const string 以避免在您的 Foo 方法中出现魔法值。如果常量只使用一次,这听起来可能不太令人信服,但如果将来有可能多次使用它,那么 DRY几乎是散弹枪论证。

更新:

在这种特定情况下(调试输出,常量保证只使用一次)我不认为常量提供任何值。我会对字符串文字进行硬编码。

关于c# - const 字符串字段与 "typed"字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15407296/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com