今天,我搜索了一行代码如下:
SomeObject.SomeFunction().SomeOtherFunction();
我无法理解这一点。我试图在Google上搜索这个但没有运气。
请帮助我理解这一点。
答案 0 :(得分:3)
SomeObject有一个名为SomeFunction()的函数。此函数根据您的示例返回一个对象(我们的类型未知)。该对象有一个名为SomeOtherFunction()的函数。
但是,“如何实施”的问题有点模糊不清。
答案 1 :(得分:2)
这称为 Fluent 编码或方法链,是一种编程方法,允许您将命令链接在一起。在LINQ中,您可能会遇到类似这样的事情:
var result = myList.Where(x => x.ID > 5).GroupBy(x => x.Name).Sort().ToList();
这将为您提供大于5的所有记录,然后按名称分组,排序并作为列表返回。可以像这样用长手写相同的代码:
var result = myList.Where(x => x.ID > 5);
result = result.GroupBy(x => x.Name);
result = result.Sort();
result = result.ToList();
但是你可以看到这是更长时间的啰嗦。
答案 2 :(得分:2)
这种编程风格称为FluentInterface样式。
例如:
internal class FluentStyle
{
public FluentStyle ConnectToDb()
{
// some logic
return this;
}
public FluentStyle FetchData()
{
// some logic
return this;
}
public FluentStyle BindData()
{
// some logic
return this;
}
public FluentStyle RefreshData()
{
// some logic
return this;
}
}
可以创建对象,并且可以按如下方式使用方法;
var fluentStyle = new FluentStyle();
fluentStyle.ConnectToDb().FetchData().BindData().RefreshData();
答案 3 :(得分:2)
考虑以下
public class FirstClass
{
public SecondClass SomeFunction()
{
return new SecondClass();
}
}
public class SecondClass
{
public void SomeOtherFunction()
{
}
}
以下是等效的。
FirstClass SomeObject = new FirstClass();
SomeObject.SomeFuntion().SomeOtherFunction();
OR
FirstClass SomeObject = new FirstClass();
SecondClass two = SomeObject.SomeFuntion();
two.SomeOtherFunction();
答案 4 :(得分:1)
这种类型的链接可能涉及扩展方法。这些允许向现有类添加新方法(即使是那些没有源代码的类)。
e.g。
public static class StringExtender
{
public static string MyMethod1(this string Input)
{
return ...
}
public static string MyMethod2(this string Input)
{
return ...
}
}
....
public string AString = "some string";
public string NewString = AString.MyMethod1().MyMethod2();
答案 5 :(得分:1)
这可以使用扩展方法
来完成 public class FirstClass
{
}
public class SecondClass
{
}
public class ThridClass
{
}
public static class Extensions
{
public static SecondClass GetSecondClass(this FirstClass f)
{
return new SecondClass();
}
public static ThridClass GetThridClass(this SecondClass s)
{
return new ThridClass();
}
}
}
然后你可以使用
FirstClass f= new FirstClass();
f.GetSecondClass().GetThridClass();