readonly struct members
void Main()
{
// See https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8
}
public struct Point
{
public double X { get; set; }
public double Y { get; set; }
// Note the readonly modifier. This will generate a compiler error if you try and modify
// the struct's fields within the method.
public readonly override string ToString() => $"({X}, {Y}) is {Distance} from the origin";
// We need a readonly modifier here to avoid a warning in the method above.
public readonly double Distance => Math.Sqrt (X * X + Y * Y);
}
default interface members
void Main()
{
ILogger foo = new Logger();
foo.Log (new Exception ("test"));
}
class Logger : ILogger
{
public void Log (string message) => Console.WriteLine (message);
}
interface ILogger
{
void Log (string message);
// Adding a new member to an interface need not break implementors:
public void Log (Exception ex) => Log (ExceptionHeader + ex.Message);
// The static modifier (and other modifiers) are now allowed:
static string ExceptionHeader = "Exception: ";
}
switch expressions
void Main()
{
var color = FromRainbow (Rainbow.Green);
new Panel { BackColor = color }.Dump();
}
public static Color FromRainbow (Rainbow colorBand) =>
colorBand switch
{
Rainbow.Red => Color.Red,
Rainbow.Orange => Color.Orange,
Rainbow.Yellow => Color.Yellow,
Rainbow.Green => Color.Green,
Rainbow.Blue => Color.Blue,
Rainbow.Indigo => Color.Indigo,
Rainbow.Violet => Color.Violet,
_ => throw new ArgumentException (message: "invalid enum value", paramName: nameof (colorBand)),
};
public enum Rainbow
{
Red,
Orange,
Yellow,
Green,
Blue,
Indigo,
Violet
}
property patterns
void Main()
{
var address = new Address { State = "WA" };
ComputeSalesTax (address, 100).Dump();
}
static decimal ComputeSalesTax (Address location, decimal salePrice) =>
location switch
{
{ State: "WA" } => salePrice * 0.06M,
{ State: "MN" } => salePrice * 0.75M,
{ State: "MI" } => salePrice * 0.05M,
// other cases removed for brevity...
_ => 0M
};
class Address
{
public string State;
}
本文作者:wwmin
微信公众号: DotNet技术说
本文链接:https://www.jianshu.com/p/ce545c355555
关于博主:评论和私信会在第一时间回复。或者[直接私信]我。
版权声明:转载请注明出处!
声援博主:如果您觉得文章对您有帮助,关注点赞, 您的鼓励是博主的最大动力!
网友评论