C# 6.0 新特性收集
2024-08-25 16:24:55
先来看一段Json.Net的代码
public JObject ToJson()
{
var result = new JObject();
result["X"] = X;
result["Y"] = Y;
return result;
}
改进后的代码可以这么写
public JObject ToJson()
{
var result = new JObject()
{
["X"] = X,
["Y"] = Y
};
return result;
}
最终可以化简成一行代码
public JObject ToJson() => new JObject() { ["X"] = X, ["Y"] = Y };
1. 静态using(static using)
1. 静态using(static using)
静态using声明允许不使用类名直接调用静态方法
C# 5
using System;
Console.WriteLine("Hello, World!");
usingstatic System.Console;
WriteLine("Hello, World");
2. 表达式方法(Expression-Bodied Methods)
In C# 5
public bool IsSquare(Rectangle rect)
{
return rect.Height == rect.Width;
}
In C# 6
public bool IsSquare(Rectangle rect) => rect.Height == rect.Width;
1. 方法(Methods)
1 public Student Create() => new Student();
等同于:
1 public Student Create()
2 {
3returnnew Student();
4 }
2. 只读属性(read only properties)
1 publicstring FullName => string.Format("{0},{1}", FirstName, LastName);
等同于:
1 publicstring FullName
2 {
3get4 {
5returnstring.Format("{0},{1}", FirstName, LastName);
6 }
7 }
原理解析:上面的表达式在编译后会生成最原始的方法体和访问器,值得一提的是函数表达式体跟Lambda是两个相似但不相同的东西,函数的表
达式体只能带一句话且不能包含return关键字但Lambda 能带语句块和包含关键字。
public Point Move(int dx, int dy) => new Point(x + dx, y + dy);
再来举一个简单的例子:一个没有返回值的函数
publicvoid Print() => Console.WriteLine(FirstName + " " + LastName);
3. 表达式属性(Expression-Bodied Properties)
跟表达式方法类似,只有一个get访问器的单行属性可以使用lambda语法写。
publicstring FullName { get { return FirstName +"" + LastName; } }
publicstring FullName => FirstName +"" + LastName;
用C#6的这个新特性,代码就会大大减小,而且可读性比起之前大大增强
4. 自动属性初始化器(Auto-Implemented Property Intializers)
In C# 5
publicclassPerson
{
publicPerson()
{
Age = 24;
}
publicint Age {get; set;}
}
In C# 6
publicclassPerson
{
publicint Age {get; set;} = 42;
}
5. 只读自动属性(Read-Only Auto Properties)
In C# 5
privatereadonlyint _bookId;
public BookId
{
get
{
return _bookId;
}
}
In C# 6
publicBookId {get;}
6. nameof操作符(nameof Operator)
字段、属性、方法和类型的name可以通过nameof访问。使用nameof,可以方便的重构name变化。
In C# 5
publicvoidMethod(object o)
{
if (o == null) thrownew ArgumentNullException("o");
}
In C# 6
publicvoidMethod(object o)
{
if (o == null) thrownew ArgumentNullException(nameof(o));
}
- public class MyClass
- {
- [TestMethod]
- public static void Show(int age)
- {
- Console.WriteLine(nameof(MyClass)); // 输出 MyClass 类名
- Console.WriteLine(nameof(Show)); // 输出 Show 方法名
- Console.WriteLine(nameof(age)); // 输出 age
- Console.WriteLine(nameof(TestMethodAttribute)) // 输出 Attribute 名
- }
- }
7. Null传递操作符(Null Propagation Operator)
int? age = p == null ? null : p.Age;
var handler = Event;
if (handler != null)
{
handler(source, e);
}
In C# 6
int? age = p?.Age;
handler?.Invoke(source, e);
8. 字符串插值(String Interpolation)
C# 6之前我们拼接字符串时需要这样
var Name = "Jack";
var results = "Hello" + Name;
或者
var Name = "Jack";
var results = string.Format("Hello {0}", Name);
WriteLine(($"{Name }"))
9. 字典初始化器(Dictionary Initializers)
In C# 5
var dict = new Dictionary<int, string>();
dict.Add(3,"three");
dict.Add(7,"seven");
In C# 6
var dict = new Dictionary<int, string>()
{
[3] ="three",
[7] ="seven"
};
10. 异常过滤器(Exception Filters)
In C# 5
try
{
//etc.
} catch (MyException ex)
{
if (ex.ErrorCode != 405) throw;
// etc.
}
In C# 6
try
{
//etc.
} catch (MyException ex) when (ex.ErrorCode == 405)
{
// etc.
}
11. 在Catch使用Await(Await in Catch)
bool hasError = false;
string errorMessage = null;
try
{
//etc.
} catch (MyException ex)
{
hasError = true;
errorMessage = ex.Message;
}
if (hasError)
{
awaitnew MessageDialog().ShowAsync(errorMessage);
}
In C# 6
try
{
//etc.
} catch (MyException ex)
{
awaitnew MessageDialog().ShowAsync(ex.Message);
}
最新文章
- 2016 GitHub章鱼猫观察报告之开源统计
- Atitit.会员卡(包括银行卡)api的设计
- 使用ASP.NET Web Api构建基于REST风格的服务实战系列教程【十】——使用CacheCow和ETag缓存资源
- 【ASP.NET 进阶】根据IP地址返回对应位置信息
- Hadoop和Spark的异同
- 获取CentOS系统详情的九个uname命令实例
- Android的Task和Activity相关
- MyEclipse 2014 + JSP+ Servlet
- java中 正则表达式的使用
- Effective Java 电子书 apk版本下载
- 创建DNS子域及view
- Linux常用命令(第二版) --帮助命令
- Linux ACL 权限
- 46 【golang项目】完成了一个小小的播放器功能
- ZolltyMVC配置-说明文档
- Theano笔记
- spring ioc beanfactory 关系图
- 背水一战 Windows 10 (41) - 控件(导航类): Frame
- 如何查看Drupal网站使用的模块
- MyBean 框架入门手册<;感谢[青铜]整理的如此细致和系统>;