C#中的这种链接叫什么?

Thi*_*ing 6 c#

你能告诉我C#中有哪种构造吗?

Code Golf:相当于Excel列名的数字

C.WriteLine(C.ReadLine() 
            .Reverse() 
            .Select((c, i) => (c - 64) * System.Math.Pow(26, i)) 
            .Sum());
Run Code Online (Sandbox Code Playgroud)

虽然我是C#的新手(到目前为止只有两个月),但自从我加入C#团队以来,我从未见过这种链接.它真的吸引了我,我想了解更多.

请对此有所了解.

Mat*_*ing 9

像这样链接的方法通常称为流畅的界面.

您可以通过实现返回调用对象的函数来创建自己的流畅界面.

对于一个简单的例子:

class Foo 
{
    private int bar;

    public Foo AddBar(int b) 
    {
        bar += b;
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

哪个可以用作:

Foo f = new Foo().AddBar(1).AddBar(2);
Run Code Online (Sandbox Code Playgroud)

您还可以使用扩展方法实现流畅的界面.

例如:

class Foo 
{
    public int Bar { get; set; }
}

static class FooExtensions 
{
    public static Foo AddBar(this Foo foo, int b)
    {
        foo.Bar += b;
        return foo;
    }
}
Run Code Online (Sandbox Code Playgroud)

等等

是一个更复杂的例子.最后,AutofacCuttingEdge.Conditons是两个具有非常好的流畅接口的开源库的例子.

  • 戴夫,你是对的,返回一个新的Foo将避免副作用.然而,在这种情况下,副作用是流畅界面的一个非常重要的组成部分.副作用是有意的. (2认同)