使用Environment.NewLine的别名
当前的最佳实践是在代码中使用Environment.NewLine,以便开始一个新行。 我希望能够在我的代码中使用别名或重载运算符,以便更简洁。 而不是这个:
MessageBox.Show("My first line here" + Environment.NewLine + "My second line here");
我想要这样的东西:
MessageBox.Show("My first line here" + NL + "My second line here");
如何轻松地将其设置为IDE设置或整个项目/命名空间?
我想到了一个别名或重载的运算符,但不确定是否有一种比Environment.NewLine更简洁的全局别名的好方法,而且之前我从未做过重载运算符,所以不熟悉来龙去脉。
简单的缩短方法。 在您的一个实用程序集中弹出此类:
namespace MyCompany { public static class E { public static readonly string NL = System.Environment.NewLine; } }
然后你可以愉快地使用它:
using MyCompany; MessageBox.Show("My first line here" + E.NL + "My second line here");
我建议您使用扩展方法吗?
public static class StringExtensions { public static string NextLine(this string s, string next) { return s + Environment.NewLine + next; } public static string NextLine(this string s) { // just add a new line with no text return s + Environment.NewLine; } }
用法:
var lines = "My first line here".NextLine("My second line here.") .NextLine("third line").NextLine();
当然,如果你愿意,你可以称之为NL
– 但可能并不清楚。
在几乎没有Environment.NewLine
情况下使用StringBuilder.AppendLine()
:
var sb = new StringBuilder(); sb.AppendLine("My first line here"); sb.AppendLine("My second line here"); MessageBox.Show(sb.ToString());
编写一个类来提供Environment.NewLine
的值作为成员,因为Jesse C. Slicer已经建议 :
namespace MyNamespace { public static class Env { public static readonly string NL = Environment.NewLine; } }
然后编写以下using
指令:
using E = MyNamespace.Env;
您可以将此using
指令添加到默认的新类模板和您使用的任何其他模板(新struct
,新interface
等)。
这是我的机器上新类模板的位置,作为一个示例来帮助您入门:
C:\ Program Files(x86)\ Microsoft Visual Studio 9.0 \ Common7 \ IDE \ ItemTemplates \ CSharp \ Code \ 1033
完成后,您应该可以在任何地方编写E.NL
来代替Environment.NewLine
。
别名不起作用 – 您可以为命名空间或类型添加别名,但不能为类型的属性设置别名。 这样可行:
using NL = System.Environment; class Program { static void Main(string[] args) { var s = NL.NewLine; } }
但这不是:
// returns: The type name 'NewLine' does not // exist in the type 'System.Environment' error using NL = System.Environment.NewLine;
重载运算符是一个有趣的想法,但是你必须使用除String
之外的其他东西。 通常人们创建一个struct
,它可以采用基本字符串值,然后重载运算符。 如果你想要做的就是替换Environment.NewLine
这不值得痛苦。 你最好按照别人的建议使用静态扩展。
另一种替代方法(如果您已经设置使用NL
)是从公共父类中删除框架中的所有类,这些类可以具有以下属性:
public class BaseParentClass { public string NL { get { return System.Environment.NewLine; } } }
然后在所有后代类的代码中,您的代码看起来就像:
public class ChildOfBaseParent { public void Show_A_Message() { MessageBox.Show("My first line here" + NL + "My second line here"); } }
当然,如果你的类不是从一个普通的父类下降,你将不得不为了这方便而重构代码库。 您需要为winform类创建并行的System.Windows.Forms.Form父级以具有相同的行为。
但是如果你有很多涉及NL的字符串连接,那绝对值得痛苦…
添加到@abatishchev响应,您可以使用StringBuilder类做很好的事情。
StringBuilder builder = new StringBuilder(); builder.Append("List:"); builder.AppendLine(); builder.Append("1. Boat") builder.Append("2. Car").AppendLine(); builder.Replace("Boat", "Jet");