英文原文:10 features in C# that you really should learn (and use!)
翻译作者:码农网 – 小峰
如果你开始探索C#或决定扩展你的知识,那么你应该学习这些有用的语言功能,这样做有助于简化代码,避免错误,节省大量的时间。
1)async / await
使用async / await-pattern允许在执行阻塞操作时解除UI /当前线程的阻塞。async / await-pattern的工作原理是让代码继续执行,即使在某些东西阻塞了执行(如Web请求)的情况下。
2)对象/数组/集合初始化器
通过使用对象、数组和集合初始化器,可以轻松地创建类、数组和集合的实例:
//一些演示类publicclassEmployee{ publicstringName { get; set;} publicDateTime StartDate { get; set;}} //使用初始化器创建employee Employee emp = newEmployee {Name= "John Smith",今年会下载 StartDate=DateTime.今年会官方在线Now()};
上面的例子在单元测试中才真正有用,但在其他上下文中应该避免,因为类的实例应该使用构造函数创建。
3)Lambdas,谓词,delegates和 闭包
在许多情况下(例如使用Linq时),这些功能实际上是必需的,确保学习何时以及如何使用它们。
4)?今年会体育官网?(空合并运算符)
?? – 运算符返回左侧,只要它不为null;那样的情况下返回右侧:
//可能为nullvarsomeValue = service. GetValue(); vardefaultValue = 23//如果someValue为null,结果将为23varresult = someValue ?? defaultValue;
?? – 运算符可以链接:
stringanybody = parm1 ?? localDefault ?? globalDefault;
并且它可以用于将可空类型转换为不可空:
vartotalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0); 5)$“{x}”(字符串插值) ——C#6

这是C#6的一个新功能,可以让你用高效和优雅的方式组装字符串:
//旧方法varsomeString = String.Format( "Some data: {0}, some more data: {1}", someVariable, someOtherVariable); //新方法varsomeString = $"Some data: {someVariable}, some more data: {someOtherVariable}";
你可以把C#表达式放在花括号之间,这使得此字符串插值非常强大。
6)?.(Null条件运算符) ——C#6
null条件运算符的工作方式如下:
//Null ifcustomer orcustomer.profile orcustomer.profile.age isnullvar currentAge = customer?.profile?.age;
没有更多NullReferenceExceptions!
7)nameof Expression ——C#6
新出来的nameof-expression可能看起来不重要,但它真的有它的价值。当使用自动重构因子工具(如ReSharper)时,你有时需要通过名称引用方法参数:
publicvoid PrintUserName( UsercurrentUser){ //The refactoring tool might miss the textual reference to current user below ifwe're renaming it if(currentUser == null) _logger. Error( "Argument currentUser is not provided"); //...}
你应该这样使用它…
publicvoidPrintUserName(User currentUser){ //The refactoring tool will not miss this...if(currentUser == null) _logger.Error( $"Argument {nameof(currentUser)}is not provided"); //...} 8)属性初始化器 ——C#6
属性初始化器允许你声明属性的初始值:
publicclassUser{ publicGuidId{ get; } = Guid. NewGuid(); // ...}

使用属性初始化器的一个好处是你不能声明一个集合:嗯,因此使得属性不可变。属性初始化器与C#6主要构造函数语法一起工作。
9)as和is 运算符
is 运算符用于控制实例是否是特定类型,例如,如果你想看看是否可能转换:
if( PersonisAdult){ //do stuff}
使用as运算符尝试将实例转换为类。如果不能转换,它将返回null:
SomeType y = x asSomeType; if(y != null){ //do stuff} 10)yield 关键字
yield 关键字允许提供带有条目的IEnumerable接口。 以下示例将返回每个2的幂,幂指数从2到8(例如,2,4,8,16,32,64,128,256):
publicstaticIEnumerable Power(intnumber, intexponent){ intresult = 1; for( inti = 0; i < exponent; i++) { result = result * number; yieldreturnresult; }}
yield返回可以非常强大,如果它用于正确方式的话。 它使你能够懒惰地生成一系列对象,即,系统不必枚举整个集合——它就会按需完成。
发表评论
评论列表
This is my third time ordering from this seller, and they never disappoint. This is my third time ordering from this seller, and they never disappoint
Great value for the price. Will definitely buy again. Fast shipping and great customer service. Very happy with my purchase.