帮助重构Action <t>委托</t>

时间:2010-01-08 23:14:17

标签: c# generics refactoring

在一个测试方法中(对于Fluent NHibernate映射,尽管这并不是真的相关),我将以下代码包含在一堆uses和try / catch块中:

new PersistenceSpecification<Entry>(session)
    .CheckProperty(e => e.Id, "1")
    .VerifyTheMappings();

我想重构这个,以便我可以将它传递给辅助方法(我放置usingtry/catch块)。

我的要求是按照我的意愿运作

  1. session需要由其中一个使用声明
  2. 提供
  3. Entry应作为通用参数提供,以便我可以测试各种对象的映射
  4. 在定义参数时(在测试方法中)应该可以将.CheckProperty(e => e.Id, "1").VerifyTheMappings()替换为PersistenceSpecification<T>上调用的任何内容。
  5. 基本上,我想做这样的事情:

    var testAction = new PersistenceSpecification<Entry>(session)
                          .CheckProperty(e => e.Id, "1")
                          .VerifyTheMappings();
    
    HelpTestMethod(testAction)
    

    但满足上述要求。

1 个答案:

答案 0 :(得分:2)

如下:

Action<PersistenceSpecification<Entry>> testAction = pspec => pspec
                .CheckProperty(e => e.Id, "1")
                .VerifyTheMappings();

HelpTestMethod<Entry>(testAction);

public void HelpTestMethod<T>(Action<PersistenceSpecification<T>> testAction)
{
    using(var session = new SessionFactory().CreateSession(...))
    {
        testAction(new PersistenceSpecification<T>( session ));
    }
}