我遇到了一个关于Full Stack .Net Web Development的教程,我从未见过使用点运算符对C#来说是这样的.有人可以解释为什么语句不以分号结尾,并且语句属于特定对象也意味着什么?
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
namespace MyApi
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
Run Code Online (Sandbox Code Playgroud)
它只是分成多行的单个语句,也是流畅的方法链接的一个例子.
每个方法调用都返回一个对象,然后可以取消引用该对象以执行另一个方法调用.
这是一个简单的例子,让您了解它是如何工作的.注意每个方法如何返回当前实例Person,即this.
class Person
{
public string Firstname { get; set; }
public string Surname { get; set; }
public DateTime DateOfBirth { get; set; }
public decimal HeightCm { get; set; }
public Person WithName(string firstname, string surname)
{
Firstname = firstname;
Surname = surname;
return this;
}
public Person BornOn(DateTime date)
{
DateOfBirth = date;
return this;
}
public Person WithHeight(decimal heightCm)
{
HeightCm = heightCm;
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作:
var person = new Person().WithName("Doctor", "Jones").BornOn(new DateTime(1980, 1, 1)).WithHeight(175);
Run Code Online (Sandbox Code Playgroud)
其中也可以表示为:
var person = new Person()
.WithName("Doctor", "Jones")
.BornOn(new DateTime(1980, 1, 1))
.WithHeight(175);
Run Code Online (Sandbox Code Playgroud)
不需要将它分成多行,但可以是风格选择,也可以是您的编码标准.
| 归档时间: |
|
| 查看次数: |
131 次 |
| 最近记录: |