什么是这种在C#中的链接叫? [英] What is this kind of chaining in C# called?

查看:126
本文介绍了什么是这种在C#中的链接叫?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

能否请你告诉我什么样的结构在C#中是这样的。

Can you please tell me what kind of construct in C# is this.

代码高尔夫:一个Excel列名的数字等效

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



虽然我是新来的C#(仅两个月EXP到目前为止),但因为我有足够的时间加入了C#的球队,我从来没有见过这种链接的。 这真的吸引了我,我想更多地了解它。

Though I am new to C# (only two months exp so far), but since the time I have joined a C# team, I have never seen this kind of chaining. It really attracted me and I want to learn more about it.

请给这个一些见解。

推荐答案

这样的方法链通常被称为流畅的界面

Method chaining like this is often called a fluent interface.

您可以通过实现回报,他们被称为对对象的功能让你自己流畅的界面。

You can make your own fluent interface by implementing functions that return the object they were called on.

对于一个简单的例子:

class Foo 
{
    private int bar;

    public Foo AddBar(int b) 
    {
        bar += b;
        return this;
    }
}



这可以像使用:

Which can be used like:

Foo f = new Foo().AddBar(1).AddBar(2);

您也可以使用扩展方法实现一个流畅的界面。

You could also implement a fluent interface using extension methods.

例如:

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

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



等。

etc.

这里是一个更为复杂的例子。最后, Autofac CuttingEdge.Conditons 是有非常好的流畅接口开放源码库的两个例子。

Here is a more complex example. Finally, Autofac and CuttingEdge.Conditons are two examples of open-source libraries that have very nice fluent interfaces.

这篇关于什么是这种在C#中的链接叫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆