1. 自动的属性初始化器Auto Property initialzier

之前的方式:

public class AutoPropertyBeforeCsharp6
{
private string _postTitle = string.Empty;
public AutoPropertyBeforeCsharp6()
{
//assign initial values
PostID = ;
PostName = "Post 1";
} public long PostID { get; set; } public string PostName { get; set; } public string PostTitle
{
get { return _postTitle; }
protected set
{
_postTitle = value;
}
}
}

C# 6 自动实现的带有初始值的属性可以不用编写构造器就能被初始化. 我们可以用下面的代码简化上面的示例:

public class AutoPropertyInCsharp6
{
public long PostID { get; } = ; public string PostName { get; } = "Post 1"; public string PostTitle { get; protected set; } = string.Empty;
}

2. 主构造器

之前的方式:

public class PrimaryConstructorsBeforeCSharp6
{
public PrimaryConstructorsBeforeCSharp6(long postId, string postName, string postTitle)
{
PostID = postId;
PostName = postName;
PostTitle = postTitle;
} public long PostID { get; set; }
public string PostName { get; set; }
public string PostTitle { get; set; }
}

有了这个特性之后的方式

public class PrimaryConstructorsInCSharp6(long postId, string postName, string postTitle)
{
public long PostID { get; } = postId;
public string PostName { get; } = postName;
public string PostTitle { get; } = postTitle;
}

在 C# 6 中, 主构造器为我们提供了使用参数定义构造器的一个简短语法. 每个类只可以有一个主构造器.

如果你观察上面的示例,会发现我们将参数初始化移动到了类名的旁边.

你可能会得到下面这样的错误“Feature ‘primary constructor’ is only available in ‘experimental’ language version.”(主构造器特性只在实验性质的语言版本中可用), 为了解决这个问题,我们需要编辑 SolutionName.csproj 文件,来规避这个错误 . 你所要做的就是在 WarningTag 后面添加额外的设置

<LangVersion>experimental</LangVersion>

‘主构造器’只在‘实验’性质的语言版本中可用

3. 字典初始化器

之前的方式:

public class DictionaryInitializerBeforeCSharp6
{
public Dictionary<string, string> _users = new Dictionary<string, string>()
{
{"users", "Venkat Baggu Blog" },
{"Features", "Whats new in C# 6" }
};
}

可以像数组里使用方括号的方式那样定义一个字典初始化器

public class DictionaryInitializerInCSharp6
{
public Dictionary<string, string> _users { get; } = new Dictionary<string, string>()
{
["users"] = "Venkat Baggu Blog",
["Features"] = "Whats new in C# 6"
};
}

4. 声明表达式

之前的方式:

public class DeclarationExpressionsBeforeCShapr6()
{
public static int CheckUserExist(string userId)
{
//Example 1
int id;
if (!int.TryParse(userId, out id))
{
return id;
}
return id;
} public static string GetUserRole(long userId)
{
////Example 2
var user = _userRepository.Users.FindById(x => x.UserID == userId);
if (user!=null)
{
// work with address ... return user.City;
}
}
}

这个特性之后的方式

public class DeclarationExpressionsInCShapr6()
{
public static int CheckUserExist(string userId)
{
if (!int.TryParse(userId, out var id))
{
return id;
}
return ;
} public static string GetUserRole(long userId)
{
////Example 2
if ((var user = _userRepository.Users.FindById(x => x.UserID == userId) != null)
{
// work with address ... return user.City;
}
}
}

5. 静态的 Using

之前的方式:

StaticUsingBeforeCSharp6.TestMethod();

public class StaticUsingBeforeCSharp6
{
public void TestMethod()
{
Console.WriteLine("Static Using Before C# 6");
}
}

在 C# 6 中,你不用类名就能使用 静态成员 . 你可以在命名空间中引入静态类.
这个特性之后的方式

using System.Console;
namespace newfeatureincsharp6
{
public class StaticUsingInCSharp6
{
public void TestMethod()
{
WriteLine("Static Using Before C# 6");
}
}
}

6. catch块里面的await

之前catch和finally块中是不能用 await 关键词的. 在 C# 6 中,我们终于可以再这两个地方使用await了

try
{
//Do something
}
catch (Exception)
{
await Logger.Error("exception logging")
}

7. 异常过滤器

异常过滤器可以让你在catch块执行之前先进行一个 if 条件判断.

看看这个发生了一个异常的示例,现在我们想要先判断里面的Exception是否为null,然后再执行catch块

//示例 1
try
{
//Some code
}
catch (Exception ex) if (ex.InnerException == null)
{
//Do work
} //Before C# 6 we write the above code as follows
//示例 1
try
{
//Some code
}
catch (Exception ex)
{
if(ex.InnerException != null)
{
//Do work;
}
}

8. 用于检查NULL值的条件访问操作符?.

之前的方式:

if(UserID != null)
{
userRank = Rank;
}
//or
var userRank = UserID != null ? Rank : "No Rank"

这个特性之后:

var userRank = UserID?.Rank ?? "No Rank";

此特性不光是可以用于取值,也可以用于方法调用

9. 字符串插值

之前的方式:

var Name = "Jack";
var results = "Hello" + Name; //或者
var Name = "Jack";
var results = string.Format("Hello {0}", Name);

这个特性之后:

var Name = "Jack";
var results = $"Hello {Name}"; //不光是可以插简单的字符串,还可以直接插入代码 Console.WriteLine($"Jack is saying { new Tools().SayHello() }"); var info = $"Your discount is {await GetDiscount()}";

10. NameOf

之前的方式:

public string Name
{
get { return name; }
set
{
name= value;
RaisePropertyChanged("Name");
}
}

这个特性之后:

public string Name
{
get { return name; }
set
{
name= value;
RaisePropertyChanged(NameOf(Name));
}
} static void Main(string[] args)
{
Console.WriteLine(nameof(User.Name));
// output: Name
Console.WriteLine(nameof(System.Linq));
// output: Linq
Console.WriteLine(nameof(List));
// output: List
Console.ReadLine();
}

注意: NameOf只会返回Member的字符串,如果前面有对象或者命名空间,NameOf只会返回 . 的最后一部分, 另外NameOf有很多情况是不支持的,比如方法,关键字,对象的实例以及字符串和表达式

转载自:http://www.oschina.net/translate/new-features-in-csharp

C# 6.0 的新特性的更多相关文章

  1. php5.3到php7.0.x新特性介绍

    <?php /*php5.3*/ echo '<hr>'; const MYTT = 'aaa'; #print_r(get_defined_constants()); /* 5.4 ...

  2. paip.php 5.0 5.3 5.4 5.5 -6.0的新特性总结与比较

    paip.php 5.0 5.3 5.4  5.5 -6.0的新特性总结与比较 PHP5的新特性 2 · 对象的参照过渡是默认的(default) 3 · 引入访问属性的限制 3 · 引入访问方法的限 ...

  3. NodeJS 框架 Express 从 3.0升级至4.0的新特性

    NodeJS 框架 Express 从 3.0升级至4.0的新特性 [原文地址:√https://scotch.io/bar-talk/expressjs-4-0-new-features-and-u ...

  4. 相比于python2.6,python3.0的新特性。

    这篇文章主要介绍了相比于python2.6,python3.0的新特性.更详细的介绍请参见python3.0的文档. Common Stumbling Blocks 本段简单的列出容易使人出错的变动. ...

  5. MySQL 8.0 InnoDB新特性

    MySQL 8.0 InnoDB新特性 1.数据字典全部采用InnoDB引擎存储,支持DDL原子性.crash safe,metadata管理更完善 2.快速在线加新列(腾讯互娱DBA团队贡献) 3. ...

  6. Atitit jquery  1.4--v1.11  v1.12  v2.0  3.0 的新特性

    Atitit jquery  1.4--v1.11  v1.12  v2.0  3.0 的新特性 1.1. Jquery1.12  jQuery 2.2 和 1.12 新版本发布 - OPEN资讯.h ...

  7. [PHP] 从PHP 5.6.x 移植到 PHP 7.0.x新特性

    从PHP 5.6.x 移植到 PHP 7.0.x 新特性: 1.标量类型声明 字符串(string), 整数 (int), 浮点数 (float), 布尔值 (bool),callable,array ...

  8. servlet3.0 的新特性之二注解代替了web.xml配置文件

    servlet3.0 的新特性: 注解代替了 web.xml 文件 支持了对异步的处理 对上传文件的支持 1.注解代替了配置文件 1.删除了web.xml 文件 2. 在Servlet类上添加@Web ...

  9. C# 6.0/7.0 的新特性

    转眼C#语言都已经迭代到7.0版本了,很多小伙伴都已经把C# 7.0 的新特性应用到代码中了,想想自己连6.0的新特性都还很少使用,今天特意搜集了一下6.0和7.0的一些新特性,记录一下,方便查阅. ...

  10. C#6.0的新特性之内插字符串

    https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/interpolated-strings C# 6 ...

随机推荐

  1. 聊聊HTTPS和SSL/TLS协议 分类: 计算机网络 2015-07-11 21:41 4人阅读 评论(0) 收藏

    要说清楚 HTTPS 协议的实现原理,至少需要如下几个背景知识. 1. 大致了解几个基本术语(HTTPS.SSL.TLS)的含义 2. 大致了解 HTTP 和 TCP 的关系(尤其是"短连接 ...

  2. 在XML里的XSD和DTD以及standalone的使用3----具体使用详解

    本人亲自写的一个简单的测试例子 1.xsd定义 <?xml version="1.0" encoding="utf-8"?><xs:schem ...

  3. R programming, In ks.test(x, y) : p-value will be approximate in the presence of ties

    Warning message: In ks.test(x, y) : p-value will be approximate in the presence of ties   The warnin ...

  4. HDU 1255 覆盖的面积 (扫描线 线段树 离散化 矩形面积并)

    题目链接 题意:中文题意. 分析:纯手敲,与上一道题目很相似,但是刚开始我以为只是把cnt>=0改成cnt>=2就行了,. 但是后来发现当当前加入的线段的范围之前 还有线段的时候就不行了, ...

  5. Fragment 和 FragmentActivity的使用(二)

      今天继续完成剩下的学习部分,现在项目很多地方使用viewpager来提供滑动,今天记录学习viewpager配合fragment的显示,增加一个CallLogsFragment配合之前SMSLis ...

  6. ha_innobase::general_fetch

    /***********************************************************************//** Reads the next or previ ...

  7. CSS效果

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs& ...

  8. bzoj1486: [HNOI2009]最小圈

    二分+dfs. 这道题求图的最小环的每条边的权值的平均值μ. 这个平均值是大有用处的,求它我们就不用记录这条环到底有几条边构成. 如果我们把这个图的所有边的权值减去μ,就会出现负环. 所以二分求解. ...

  9. ubuntu下安装mysql及外网访问设置

    这么多年一直是mssql或者Oracle,mysql基本没用过,借着.net即将跨平台之际,也mysql一把.windows安装基本没啥难度,然后就是试了把linux下...结果坑不少,由于linux ...

  10. 《分销系统-原创第一章》之“多用户角色权限访问模块问题”的解决思路( 位运算 + ActionFilterAttribute )

    此项目需求就是根据给用户分配的权限,进行相应的权限模块浏览功能,因为项目不是很大,所以权限没有去用一张表去存,我的解决思路如下,希望大家给点建议. 数据库用户表结构如下: 数据库表梳理: BankUs ...