C# 6.0 (C# vNext) 新功能之:Expression Bodied Functions and Properties
2014-10-14 13:55
483 查看
Expression Bodied Function 可以用在:
methods
user-defined operators
type conversions
read-only properties
indexers
看以下的例子:
用於「方法」的例子:
用於「user-defined operators」的例子:
用於「read-only property」的例子:
特别注意,这是 Read Only Property 而不是 Field
用於「type conversions」的例子:实现 string 和 Name 之间的隐性转换
用於「indexers」的例子:
methods
user-defined operators
type conversions
read-only properties
indexers
看以下的例子:
public class RgbColor(int r, int g, int b) { public int Red { get; } = r; public int Green { get; } = g; public int Blue { get; } = b; public string ToHex() => string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue); public static RgbColor operator - (RgbColor color) => new RgbColor( color.Red ^ 0xFF, color.Green ^ 0xFF, color.Blue ^ 0xFF ); }
用於「方法」的例子:
public string ToHex() => string.Format("#{0:X2}{1:X2}{2:X2}", Red, Green, Blue); public override string ToString() => this.Name;
用於「user-defined operators」的例子:
public static RgbColor operator - (RgbColor color) => new RgbColor( color.Red ^ 0xFF, color.Green ^ 0xFF, color.Blue ^ 0xFF );
public static Complex operator +(Complex a, Complex b) => a.Add(b);
用於「read-only property」的例子:
特别注意,这是 Read Only Property 而不是 Field
public string ID => Guid.NewGuid().ToString();又一个例子:
public class Point(int x, int y) { public int X => x; public int Y => y; public double Dist => Math.Sqrt(x * x + y * y); public Point Move(int dx, int dy) => new Point(x + dx, y + dy); }
用於「type conversions」的例子:实现 string 和 Name 之间的隐性转换
public static implicit operator string(Name n) => n.First + " " + n.Last;
用於「indexers」的例子:
public Customer this[Id id] => store.LookupCustomer(id);
相关文章推荐
- C# 6.0 (C# vNext) 的新功能:Expression Bodied Functions and Properties
- C# 6.0 (C# vNext) 新功能之:Indexed Members and Element Initializers 索引的成員和元素初始化
- C# 6.0 (C# vNext) 新功能之:Auto-Properties with Initializers
- C# 6.0 (C# vNext) 新功能之:Event initializers
- C# 6.0 (C# vNext) 新功能之:Exception-Handling Improvements
- C# 6.0 (C# vNext) 新功能之:Null-Conditional Operator
- C# 6.0 (C# vNext) 的新功能:Exception-Handling Improvements
- C# 6.0 (C# vNext) 新功能之:Primary Constructors 主要的构造函式
- C# 6.0 (C# vNext) 新功能之:Numeric Literal Formats
- C# 6.0 (C# vNext) 新功能之:Static Using Statements
- C# 6.0 (C# vNext) 新功能之:Nameof Expressions
- C# 6.0 (C# vNext) 新功能之:Semicolon operator
- C# 6.0 (C# vNext) 新功能之:Declaration Expressions
- PHP String and Regular Expression functions
- C# 6.0 新功能Top 10
- Properties and Indexers in C#
- An article about Equals and GetHashCode functions in C#
- Gene Expression Programming (GEP) in C# and .NET
- 【资源】【下载】C# 6.0 and the .NET 4.6 Framework 7th ed. Edition
- Effective C# Item 20: Distinguish Between Implementing Interfaces and Overriding Virtual Functions