visual studio 2017安裝完后,馬上全面體驗下C# 7.0。
- out variables (out變量)
out的形參變量無需再提前聲明
之前:
string input = "3";
int numericResult;
if (int.TryParse(input, out numericResult))
Console.WriteLine(numericResult);
else
Console.WriteLine("Could not parse input");
現在:
string input = "3";
if (int.TryParse(input, out var numericResult))
Console.WriteLine(numericResult);
else
Console.WriteLine("Could not parse input");
- Tuples (元組)
擴展了元組(Tuple的使用,需要Nuget引用 System.ValueTuple)
1.命名的改進:
無命名,僅能通過無意義的Item1,Item2進行訪問:
var letters = ("a", "b");
Console.WriteLine($"Value is {letters.Item1} and {letters.Item2>}");
以前版本的命名:
(string first, string second) letters = ("a", "b");
Console.WriteLine($"Value is {letters.first} and {letters.second}");
現在的命名:
var letters = (first: "a",second: "b");
Console.WriteLine($"Value is {letters.first} and {letters.second}");
現在混合型命名:(會有一個編譯警告,僅以左側命名為准)
(string leftFirst,string leftSecond) letters = (first: "a", second: "b");
Console.WriteLine($"Value is {letters.leftFirst} and {letters.leftSecond}");
2.函數返回元組、對象轉元組
示例1:
static void Main(string[] args)
{
var p = GetData();
Console.WriteLine($"value is {p.name} and {p.age}");
}
private static (string name,int age) GetData()
{
return ("han mei", 23);
}
示例2:(注意類中應實現Deconstruct用於元組的轉換)
class Program
{
static void Main(string[] args)
{
var p = new Point(1.1, 2.1);
(double first, double second) = p;
Console.WriteLine($"value is {first} and {second}");
}
}
public class Point
{
public Point(double x, double y)
{
this.X = x;
this.Y = y;
}
public double X { get; }
public double Y { get; }
public void Deconstruct(out double x, out double y)
{
x = this.X;
y = this.Y;
}
}
- Local function (本地函數)
可以在函數內部聲明函數
示例:
static void Main(string[] args)
{
var v = Fibonacci(3);
Console.WriteLine($"value is {v}");
}
private static int Fibonacci(int x)
{
if (x < 0) throw new ArgumentException("Less negativity please!", nameof(x));
return Fib(x).current;
(int current, int previous) Fib(int i)
{
if (i == 0) return (1, 0);
var (p, pp) = Fib(i - 1);
return (p + pp, p);
}
}
- Literal improments(字義改進)
1.數字間可以增加分隔符:_ (增加可讀性)
2.可以直接聲明二進制 (使用二進制的場景更方便,比如掩碼、用位進行權限設置等)
示例:
var d = 123_456; var x = 0xAB_CD_EF; var b = 0b1010_1011_1100_1101_1110_1111;
- Ref returns and locals (返回引用)
返回的變量可以是一個引用。
示例:
static void Main(string[] args)
{
int[] array = { 1, 15, -39, 0, 7, 14, -12 };
ref int place = ref Find(7, array); // aliases 7's place in the array
place = 9; // replaces 7 with 9 in the array
Console.WriteLine(array[4]); // prints 9
}
private static ref int Find(int number, int[] numbers)
{
for (int i = 0; i < numbers.Length; i++)
{
if (numbers[i] == number)
{
return ref numbers[i]; // return the storage location, not the value
}
}
throw new IndexOutOfRangeException($"{nameof(number)} not found");
}
- More expression bodied members(更多的表達式體的成員)
支持更多的成員使用表達式體,加入了訪問器、構造函數、析構函數使用表達式體
示例:
class Person
{
private static ConcurrentDictionary<int, string> names = new ConcurrentDictionary<int, string>();
private int id = 123;
public Person(string name) => names.TryAdd(id, name); // constructors
~Person() => names.TryRemove(id, out var v); // destructors
public string Name
{
get => names[id]; // getters
set => names[id] = value; // setters
}
}
- Throw expressions(拋出表達式)
將異常直接作為表達式拋出,不管是用表達式體時,還是普通的return 時可以直接作為一個表達式來寫。
示例:(可以看到,很方便的直接進行值判斷然后拋出異常)
class Person
{
public string Name { get; }
public Person(string name) => Name = name ?? throw new ArgumentNullException(name);
public string GetFirstName()
{
var parts = Name.Split(' ');
return (parts.Length > 0) ? parts[0] : throw new InvalidOperationException("No name!");
}
public string GetLastName() => throw new NotImplementedException();
}
- Generalized async return types(全面異步返回類型)
需要Nuget引用System.Threading.Tasks.Extensions。異步時能返回更多的類型。
示例:
public async ValueTask<int> Func()
{
await Task.Delay(100);
return 5;
}
- Pattern matching(模式匹配)
1. is 表達式 ,判斷類型的同時創建變量
示例:
public static int DiceSum2(IEnumerable<object> values)
{
var sum = 0;
foreach(var item in values)
{
if (item is int val)
sum += val;
else if (item is IEnumerable<object> subList)
sum += DiceSum2(subList);
}
return sum;
}
2. switch 表達式,允許case后的條件判斷的同時創建變量
示例:
public static int DiceSum5(IEnumerable<object> values)
{
var sum = 0;
foreach (var item in values)
{
switch (item)
{
case 0:
break;
case int val:
sum += val;
break;
case PercentileDie die:
sum += die.Multiplier * die.Value;
break;
case IEnumerable<object> subList when subList.Any():
sum += DiceSum5(subList);
break;
case IEnumerable<object> subList:
break;
case null:
break;
default:
throw new InvalidOperationException("unknown item type");
}
}
return sum;
}
參考內容:https://docs.microsoft.com/en-us/dotnet/articles/csharp/csharp-7
