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
}

下面是两个示例调用者,一个使用范围变量:

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

看看你的问题,我建议在这里使用方法重载,而不是尝试制作一些漂亮的方法来获得一个适合所有消费者的方法签名。

于 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

老实说,我推荐这样做,但它可能对那些快速而肮脏的时刻之一有用。

您可以更改方法签名并添加可选参数:

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 回答