Effective C#:改善C#代码的50个有效方法(1)
目录
第1章 C#语言的编程习惯
第1条:优先使用隐式类型的局部变量目录
-
注意力放在变量的语意上,而不是类型上。
var HighestSellingProduct = someObject.DoSomeWork(anotherParameter); -
防止窄化转换。
var total = 100 * f / 6; -
即使指定类型,仍有窄化的问题,因此要使用更清晰的表达式。
var total = 100 * f / 6.0; -
让编译器自己选择最优的类型。如 q 的类型为IQueryable
,比类型为IEnumerable 效率更高。 var q = from c in db.Customers select c.ContactName;
第2条:考虑使用readonly代替const
-
编译期常量,编译时确定值,性能较好。只能使用数字、字符串或null来初始化。
// Compile-time constant: public const int Millennium = 2000; -
运行期常量,运行时确定值,灵活性高。类型不受限制。
// Runtime constant: public static readonly int ThisYear = 2000; -
跨程序集使用时,编译器常量如果改变,所有涉及的程序集都需要重新编译
-
性能工具:BenchmarkDotNet
第3条:有限考虑is或as运算符,尽量少用强制类型转换
第4条:用内插字符串取代string.Format()
-
以美元符($)打头:,在花括号内({})写表达式
-
在冒号后面设置格式
Console.WriteLine($"The value of pi is {Math.PI:F2}"); -
只能使用表达式,不能使用语句,不能出现冒号(:):
Console.WriteLine($@"The value of pi is {(round ? Math.PI.ToString() : Math.PI.ToString("F2"))}"); -
使用null合并运算符与null条件运算符
Console.WriteLine($"The customer's name is {c?.Name ?? "Name is missing"}"); -
内插字符串里仍支持内插字符串
string result = default(string); Console.WriteLine($@"Record is {(Record is {(records.TryGetValue(index, out result) ? result : $"No record found at index {index}")})}"); -
使用LINQ查询
var output = $@"The First five items are: {src.Take(5).Select( n => $@"Item: {n.ToString()}").Aggregate( (c, a) => $@"{c}{Environment.NewLine}{a}")};
第5条:用FormattableString取代专门为特定区域而写的字符串
-
获取FormattableString类型的字符串
FormattableString second = $"It's the {DateTime.Now.Day} of the {DateTime.Now.Month} month, PI: {Math.PI:F6}"; -
获取特定区域的字符串
public static string ToGerman(FormattableString src) { return string.Format(System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"), src.Format, src.GetArguments()); }
posted on 2021-09-18 08:35 OctoberKey 阅读(214) 评论(0) 收藏 举报
浙公网安备 33010602011771号