0

関数を取るメソッド(読みやすくするために削除)があります:

private TestEntityContainer CreateTestEntityContainer(string rootName,
        Func<InstallationSummary, DateTime> forceInstallationTimeFunc,
        bool forceInstallEnvironmentShouldMatch, bool freezeAllInstallations, int numberOfInstallationSummariesToCreate)
{   
    // Other code exists above here. Note that we use two variables, appServer and appWithGroup,
    // created earlier in this method, here:
    var mostRecentInstallationSummary = InstallationSummaryLogic.GetMostRecentByServerAppAndGroup(appServer, appWithGroup);

    var forceInstallation = new ForceInstallation();
    // This is where the func is invoked. We need other things, created above, for this to work.
    forceInstallation.ForceInstallationTime = forceInstallationTimeFunc.Invoke(mostRecentInstallationSummary);
    // Do more things with forceInstallation here
}

以下に 2 つの呼び出し元の例を示します。1 つは範囲変数を使用します。

var container = CreateTestEntityContainer("UseCase12", x => x.InstallationStart.AddSeconds(1), true, false, 5);

そして、そうでないもの:

var container = CreateTestEntityContainer("UseCase10", x => DateTime.Now.AddDays(-1), false, false, 0);

それはハックのようです。多くの場合、消費者が不要な関数を使用する必要がない場合に、これを解決するより良い方法はありますか?

4

4 に答える 4

1

あなたの問題を見て、私はここでメソッドのオーバーロードを使用することをお勧めします。すべてのコンシューマーに合うように1つのメソッドシグネチャを取得するための気の利いた方法を作成しようとするのではありません。

于 2013-02-21T17:52:19.213 に答える
1

関数に のインスタンスを与える代わりに、Fooを作成する機能を持つ関数を与えることができますFoo

private TestEntityContainer CreateContainer(Func<Func<Foo>, DateTime> func) {
  Func<Foo> creator = () => new Foo();
  forceInstallation.ForceInstallationTime = func.Invoke(creator);
}

これで、消費者はFoo必要に応じて以下を作成できます。

var container = CreateContainer(x => x().InstallationStart.AddSeconds(1));
于 2013-02-21T17:57:02.750 に答える
0

CreateContainerパラメータをとらないFuncでのオーバーロードを追加できますか?何かのようなもの:

private TestEntityContainer CreateContainer(Func<DateTime> func)
{   
    forceInstallation.ForceInstallationTime = func.Invoke();
}

var container = CreateContainer(() => DateTime.Now.AddDays(-1));
于 2013-02-21T17:51:52.003 に答える
0

正直なところ、私はこれをお勧めしませんが、それらの迅速で汚い瞬間の1つに役立つかもしれません.

メソッドのシグネチャを変更し、オプションのパラメーターを追加できます。

CreateTestEntityContainer(string s, bool forceInstallEnvironmentShouldMatch,
    bool freezeAllInstallations, int numberOfInstallationSummariesToCreate , 
    Func<InstallationSummary, DateTime> f = null)

そして、次の場合にのみ関数を使用しますf != null

次に、次のように呼び出すことができます。

var firstContainer = CreateTestEntityContainer("UseCase12", true, false, 5,  x => x.InstallationStart.AddSeconds(1));
var secondContainer = CreateTestEntityContainer("UseCase10", false, false, 0);
于 2013-02-21T19:04:54.000 に答える