今日、次のように書かれたコード行を検索しました。
SomeObject.SomeFunction().SomeOtherFunction();
私はこれを理解することができません。これについてGoogleで検索しようとしましたが、うまくいきませんでした。
これを理解するのを手伝ってください。
今日、次のように書かれたコード行を検索しました。
SomeObject.SomeFunction().SomeOtherFunction();
私はこれを理解することができません。これについてGoogleで検索しようとしましたが、うまくいきませんでした。
これを理解するのを手伝ってください。
SomeObject には SomeFunction() という関数があります。この関数はオブジェクトを返します(あなたの例に基づいて、私たちにとっては未知のタイプです)。このオブジェクトには SomeOtherFunction() という関数があります。
ただし、「どのように実装するか」という質問は、答えるのが少しあいまいです。
これは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();
しかし、これははるかに長い道のりであることがわかります。
このスタイルのプログラミングは、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();
次のことを考慮してください
public class FirstClass
{
public SecondClass SomeFunction()
{
return new SecondClass();
}
}
public class SecondClass
{
public void SomeOtherFunction()
{
}
}
したがって、以下は同等です。
FirstClass SomeObject = new FirstClass();
SomeObject.SomeFuntion().SomeOtherFunction();
また
FirstClass SomeObject = new FirstClass();
SecondClass two = SomeObject.SomeFuntion();
two.SomeOtherFunction();
これは、拡張メソッドを使用して行うことができます
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();