转载地址:http://blog.youkuaiyun.com/hetoby/article/details/77897449?locationNum=4&fps=1
1.C# 7.0特性
(1)out变量定义
#region out-variables(Out变量)
{
//out变量可以边使用边声明int b
string a = "1";
int.TryParse(a, out int b);
Console.WriteLine(b);
}
#endregion
(2)Tuples元组变化
//1).要使用,需要通过NuGet下载System.ValueTuple包
//2).声明和访问元素
private static (string a, string b, string c) GetFullName()
{
return ("a", "b", "c");
}
static void Main(string[] args)
{
var data = GetFullName();
Console.WriteLine(data.a + data.b + data.c);
}
(3)is判断时就能赋值
#region is在判断的时候就能赋值
{
object a= 1;
if (a is int b)//如果a是int类型的就将其赋值给b,而且不用定义b
{
int c = b + 10;
Console.WriteLine(c);
}
}
#endregion
(4)switch可以区分类型以及筛选
#region switch可以区分类型以及进一步筛选
{
dynamic a="";
int ads = 2;
switch (a)
{
case int b://可以区分a的类型
break;
case string c when c.Length>10 && ads>1://可以在区分类型后对该类型的数据进行筛选
break;
default:
break;
}
}
#endregion
(5)ref的变量引用返回
#region ref的引用返回
{
int a = 1;
ref int b = ref a;
b = 20;//对b进行赋值,也会对a进行赋值,两者联动
Console.WriteLine(a);
}
#endregion
(6)函数内嵌套函数
#region 局部函数
public void Test()
{
int GetIntAdd(int a)//在方法内定义方法,可以无视原方法的执行顺序
{
return ++a;
}
int b = 4;
Console.WriteLine(GetIntAdd(b));
}
#endregion
2.C# 6特性
(1)在声明的时候就可以初始化,还能初始化简单方法
(2)public ICollection<double> Grades { get; } = new List<double>(); public Standing YearInSchool { get; set;} = Standing.Freshman; public override string ToString() => $"{FullName}";
using static导入类的静态方法;using则导入namespace里的所有。
最好的一个例子是System.Math,因为它里面没有实例方法。以前不能using System.Math,因为System.Math不是namespace;
现在可以using static System.Math,因为using static可以导入类的静态方法。
注意即使一个类不全是静态方法,也可以用这种方法导入它的静态方法,比如System.String。
(3)//注意Math和String都是类 using static System.Math; Sqrt(2); using static System.String;//注意要使用String而不是string if (IsNullOrWhiteSpace(lastName)) { }
访问对象之前通常都需要判空以免引用空对象。null条件操作符”?.”提供了方便。
//person为null,则返回null;否则返回person.FirstName //表达式的返回类型为null或者string var first = person?.FirstName; //经常和null coalescing operator(??)一起使用 //表达式的返回类型为string var first = person?.FirstName ?? "Unspecified";