代码之家  ›  专栏  ›  技术社区  ›  Laurence Wingo

c#中的起始点符号是什么?

c#
  •  0
  • Laurence Wingo  · 技术社区  · 7 年前

    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();
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  5
  •   Doctor Jones    7 年前

    它只是一条跨多行拆分的语句,也是fluent方法链接的一个示例。

    每个方法调用返回一个对象,然后可以取消引用该对象以执行另一个方法调用。

    下面是一个简单的例子,让您了解它是如何工作的。请注意每个方法如何返回的当前实例 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;
        }
    }
    

    然后,您可以执行以下操作:

    var person = new Person().WithName("Doctor", "Jones").BornOn(new DateTime(1980, 1, 1)).WithHeight(175);
    

    也可以表示为:

    var person = new Person()
        .WithName("Doctor", "Jones")
        .BornOn(new DateTime(1980, 1, 1))
        .WithHeight(175);
    

    将其拆分为多行是不必要的,但可能是一种风格选择,也可能是由您的编码标准决定的。