有没有办法在 C# 中注释掉字符串的一部分?
Is there a way to comment out a part of a string in c#?
我在这里得到了这个代码部分:
label1.Text = $"Score: {score} | Speed: {speed}";
这显示了我制作的突破游戏的得分和速度。现在我不需要速度,我想知道是否有一种方法可以注释掉字符串的一部分。
当然可以
label1.Text = $"Score: {score}";// | Speed: {speed};
但也许还有另一种方法,这样可以更轻松地删除评论。像
label1.Text = $"Score: {score} #comment | Speed: {speed} #endcomment";
或
label1.Text = $"Score: {score} #/*| Speed: {speed} #*/";
因此更易于阅读和更改
您可以像这样在两行中定义字符串:
label1.Text = $"Score: {score}";
label1.Text += $" | Speed: {speed}";
所以你可以这样评论:
label1.Text = $"Score: {score}";
//label1.Text += $" | Speed: {speed}";
创建一种过滤方法,returns 仅过滤您需要的方法:
public static string Filter(string input, params string[] items)
{
return string.Join("|",input.Split('|').Where(x => items.Contains(x.Split(':')[0].Trim())));
}
现在你可以得到它:
string text = $"Score: {score} | Speed: {speed}";
Label1.Text = Filter(text, "Score");
或
Label1.Text = Filter(text, "Speed");
或
Label1.Text = Filter(text, "Score", "Speed");
您可以使用 preprocessor directives:
而不是注释掉
#if DEBUG
label1.Text = $"Score: {score} | Speed: {speed}";
#else
label1.Text = $"Score: {score}";
#endif
DEBUG 应该在调试模式下定义。这是 Visual Studio 中的默认设置。所以你不需要总是评论进出,记住不要让它溜进发布输出。
注意不要过度使用它。有很多这样的东西会使你的代码变得混乱,并使它在很长的 运行 中变得不可读(和维护地狱)。不过,对于像此处这样的特定小用途,应该没问题。
我在这里得到了这个代码部分:
label1.Text = $"Score: {score} | Speed: {speed}";
这显示了我制作的突破游戏的得分和速度。现在我不需要速度,我想知道是否有一种方法可以注释掉字符串的一部分。
当然可以
label1.Text = $"Score: {score}";// | Speed: {speed};
但也许还有另一种方法,这样可以更轻松地删除评论。像
label1.Text = $"Score: {score} #comment | Speed: {speed} #endcomment";
或
label1.Text = $"Score: {score} #/*| Speed: {speed} #*/";
因此更易于阅读和更改
您可以像这样在两行中定义字符串:
label1.Text = $"Score: {score}";
label1.Text += $" | Speed: {speed}";
所以你可以这样评论:
label1.Text = $"Score: {score}";
//label1.Text += $" | Speed: {speed}";
创建一种过滤方法,returns 仅过滤您需要的方法:
public static string Filter(string input, params string[] items)
{
return string.Join("|",input.Split('|').Where(x => items.Contains(x.Split(':')[0].Trim())));
}
现在你可以得到它:
string text = $"Score: {score} | Speed: {speed}";
Label1.Text = Filter(text, "Score");
或
Label1.Text = Filter(text, "Speed");
或
Label1.Text = Filter(text, "Score", "Speed");
您可以使用 preprocessor directives:
而不是注释掉#if DEBUG
label1.Text = $"Score: {score} | Speed: {speed}";
#else
label1.Text = $"Score: {score}";
#endif
DEBUG 应该在调试模式下定义。这是 Visual Studio 中的默认设置。所以你不需要总是评论进出,记住不要让它溜进发布输出。
注意不要过度使用它。有很多这样的东西会使你的代码变得混乱,并使它在很长的 运行 中变得不可读(和维护地狱)。不过,对于像此处这样的特定小用途,应该没问题。