[英]What is the beginning dot notation in c#?
I came across a tutorial on Full Stack .Net Web Development and I've never seen the use of the dot operator is this way for C# as of yet. 我遇到了有关Full Stack .Net Web开发的教程,到目前为止,我还从未见过将点运算符用于C#。 Can someone explain what it means in regards to why don't the statements end in semicolons and also do the statements belong to a specific object?
有人可以解释为什么语句不以分号结尾,并且语句也属于特定对象吗?
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();
}
}
}
It is simply a single statement split across multiple lines, and also an example of fluent method chaining. 它只是一条简单的语句,分成多行,并且是流利的方法链的示例。
Each method call returns an object, which then can be de-referenced to perform another method call. 每个方法调用都返回一个对象,然后可以取消引用该对象以执行另一个方法调用。
Here's a simple-ish example to give you an idea of how it works. 这是一个简单的示例,可让您了解其工作原理。 Note how each method returns the current instance of
Person
, ie this
. 注意每种方法如何返回
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;
}
}
You can then do the following: 然后,您可以执行以下操作:
var person = new Person().WithName("Doctor", "Jones").BornOn(new DateTime(1980, 1, 1)).WithHeight(175);
Which can also be expressed as: 也可以表示为:
var person = new Person()
.WithName("Doctor", "Jones")
.BornOn(new DateTime(1980, 1, 1))
.WithHeight(175);
Splitting it across multiple lines is not necessary, but could either be a stylistic choice, or dictated by your coding standards. 不必将其分成多行,但可以是一种样式选择,也可以由您的编码标准决定。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.