C#中10个你真的应该学习(和使用!)的功能

来源:互联网 发布:ubuntu 休眠 编辑:程序博客网 时间:2024/05/18 02:42

原文链接:http://52csharp.com/873.html

如果你开始探索C#或决定扩展你的知识,那么你应该学习这些有用的语言功能,这样做有助于简化代码避免错误节省大量的时间

1)async / await

使用async / await-pattern允许在执行阻塞操作时解除UI /当前线程的阻塞。async / await-pattern的工作原理是让代码继续执行,即使在某些东西阻塞了执行(如Web请求)的情况下。

阅读更多有关async / await-pattern的信息,请访问:https://msdn.microsoft.com/en-us/library/hh191443.aspx

2)对象/数组/集合初始化器
通过使用对象、数组和集合初始化器,可以轻松地创建类、数组和集合的实例:

//一些演示类public class Employee {         public string Name {get; set;}          public DateTime StartDate {get; set;} }//使用初始化器创建employee Employee emp = new Employee {    Name="John Smith",     StartDate=DateTime.Now()};

上面的例子在单元测试中才真正有用,但在其他上下文中应该避免,因为类的实例应该使用构造函数创建。

阅读更多有关初始化器的信息,请访问:https://msdn.microsoft.com/en-us/library/bb384062.aspx

3)Lambdas,谓词,delegates和闭包

在许多情况下(例如使用Linq时),这些功能实际上是必需的,确保学习何时以及如何使用它们。

阅读更多关于Lambdas,谓词,delegates和闭包的信息,请访问:http://www.codeaddiction.net/articles/13/lambda-expressions-delegates-predicates-and-closures-in-c

4)??(空合并运算符)

?? – 运算符返回左侧,只要它不为null;那样的情况下返回右侧:

//可能为nullvar someValue = service.GetValue();var defaultValue = 23;//如果someValue为null,结果将为23var result = someValue ?? defaultValue;

?? – 运算符可以链接:

string anybody = parm1 ?? localDefault ?? globalDefault;

并且它可以用于将可空类型转换为不可空:

var totalPurchased = PurchaseQuantities.Sum(kvp => kvp.Value ?? 0);

阅读更多有关?? – 运算符的信息,请访问:https://msdn.microsoft.com/en-us/library/ms173224.aspx

5)$“{x}”(字符串插值) ——C#6

这是C#6的一个新功能,可以让你用高效和优雅的方式组装字符串:

//旧方法var someString = String.Format("Some data: {0}, some more data: {1}", someVariable, someOtherVariable);//新方法var someString = $"Some data: {someVariable}, some more data: {someOtherVariable}";

你可以把C#表达式放在花括号之间,这使得此字符串插值非常强大。

6)?.(Null条件运算符) ——C#6

null条件运算符的工作方式如下:

//Null if customer or customer.profile or customer.profile.age is nullvar currentAge = customer?.profile?.age;

7)nameof Expression ——C#6

新出来的nameof-expression可能看起来不重要,但它真的有它的价值。当使用自动重构因子工具(如ReSharper)时,你有时需要通过名称引用方法参数:

public void PrintUserName(User currentUser) {    //The refactoring tool might miss the textual reference to current user      below if we're renaming it    if(currentUser == null)         _logger.Error("Argument currentUser is not provided");    //...}

你应该这样使用它…

public void PrintUserName(User currentUser){    //The refactoring tool will not miss this...     if(currentUser == null)         _logger.Error($"Argument {nameof(currentUser)} is not provided");    //...}

阅读更多有关nameof-expression的信息,请访问:https://msdn.microsoft.com/en-us/library/dn986596.aspx

8)属性初始化器 ——C#6
属性初始化器允许你声明属性的初始值

public class User{          public Guid Id { get; } = Guid.NewGuid();    // ...}

使用属性初始化器的一个好处是你不能声明一个集合:嗯,因此使得属性不可变。属性初始化器与C#6主要构造函数语法一起工作。

9)as和is 运算符

is 运算符用于控制实例是否是特定类型,例如,如果你想看看是否可能转换:

if (Person is Adult) {    //do stuff}

使用as运算符尝试将实例转换为类。如果不能转换,它将返回null:

SomeType y = x as SomeType;if (y != null) {   //do stuff}

10)yield 关键字
yield 关键字允许提供带有条目的IEnumerable接口。 以下示例将返回每个2的幂,幂指数从2到8(例如,2,4,8,16,32,64,128,256):

public static IEnumerable Power(int number, int exponent){    int result = 1;    for (int i = 0; i < exponent; i++)     {       result = result * number;      yield return result;     } }

yield返回可以非常强大,如果它用于正确方式的话。 它使你能够懒惰地生成一系列对象,即,系统不必枚举整个集合——它就会按需完成。

原创粉丝点击