C Sharp语法
外观
C# 5.0的特性
Async
async和await是一对语法糖,允许开发人员非常轻松的调用基于TASK的异步编程。async-await关键字并不会真的创建一个线程池任务,完成这个动作依赖于被调用方法中的函数。
Caller info attributes
CallerInfoAttributes用于调试时访问调用者的信息。包括三个主要的类:
- [CallerMemberName] :返回调用函数的名称。
- [CallerFilePath] :返回调用函数所在源文件全路径信息 。
- [CallerLineNumber] :返回调用函数调用具体行号。
using System;
using System.Runtime.CompilerServices;
namespace TestPro
{
class Program
{
public static void Main()
{
Log("Test.");
}
// 对日志消息进行记录,同时所有内容均有默认值,如果获取失败,则使用默认值。
public static void Log(string message,
[CallerMemberName] string callerName = "unknown",
[CallerFilePath] string callerFilePath = "unknown",
[CallerLineNumber] int callerLineNumber = -1)
{
Console.WriteLine("Message: {0}", message);
Console.WriteLine("Caller's Name: {0}", callerName);
Console.WriteLine("Caller's FilePath: {0}", callerFilePath);
Console.WriteLine("Caller's LineNumber: {0}", callerLineNumber);
}
}
}
/*
程序执行以后会显示以下内容。
Message: Test.
Caller Name: Main
Caller FilePath: C:UsersAdministratorsource
eposTestProProgram.cs
Caller Line number: 10
请按任意键继续. . .*/
绑定运算符
- =: 绑定运算符简化了数据绑定
comboBox1.Text :=: textBox1.Text; //将文本框的内容绑定到下拉框。
带参数的泛型构造函数
这个的加入给一些设计增加了强大功能,泛型早在C#2.0加入后就有着强大的应用,一般稍微设计比较好的框架,都会用到泛型,C#5.0加入带参数泛型构造函数,则在原有基础上对C#泛型完善了很多。
class MyClass<T>
where T : class, new ()
{
public MyClass()
{
this.MyObject = new T();
}
T MyObject { get; set; }
}
case支持表达式
以前case里只能写一个具体的常量,而现在可以加表达式
switch(myobj){
case string.IsNullorEmpty(myotherobj):
.....
case myotherobj.Trim().Lower:
....
}
扩展属性
[Associate(string)]
public static int MyExtensionProperty { get;set;}
支持null类型运算
int x? = null;
int y? = x + 40;
Myobject obj = null;
Myotherobj obj2 = obj.MyProperty ??? new Myotherobj();