将非实例化的类和接口传递给泛型方法

时间:2018-05-03 22:25:13

标签: c# generics interface

我继承了数百个这样的陈述:

mockKernel.Setup(x => x.Bind<IAddressService>().To<AddressService>())
          .Returns(new BindingConfigurationBuilder<AddressService>(bindingConfiguration, "ServiceName", mockKernel.Object));

...作为数百个与此类似的陈述的测试的一部分:

_kernel.Bind<IAddressService>().To<AddressService>().InRequestScope();

我想写这样的东西:

private void SetupBindAtoB<TInterface, TImplementation>(TInterface a, TImplementation b)
    where TImplementation : TInterface
{
  mockKernel.Setup(x => x.Bind<TInterface>().To<TImplementation>())
            .Returns(new BindingConfigurationBuilder<TImplementation>(bindingConfiguration, "ServiceName", mockKernel.Object));
}

...然后像这样调用它:

SetupBindAtoB(IAddressService, AddressService);

但我不能。我必须将一个真实的对象传递给SetupBindAtoB,如下所示:

SetupBindAtoB((IAddressService) null, (AddressService) null);

是否可以避免创建要传递给SetupBindAtoB的真实对象?

2 个答案:

答案 0 :(得分:2)

你试过这个吗?

private void SetupBindAtoB<TInterface, TImplementation>()
    where TImplementation : TInterface
{
  mockKernel.Setup(x => x.Bind<TInterface>().To<TImplementation>())
            .Returns(new BindingConfigurationBuilder<TImplementation>(bindingConfiguration, "ServiceName", mockKernel.Object));
}

<强>用法

SetupBindAtoB<IAddressService,AddressService>();

答案 1 :(得分:1)

您有两个未使用的参数参数(TInterface aTImplementation b)。只有类型参数本身(IInterfaceIImplementation)是相关的。所以只需删除不必要的参数:

private void SetupBindAtoB<TInterface, TImplementation>()
    where TImplementation : TInterface
{
  mockKernel.Setup(x => x.Bind<TInterface>().To<TImplementation>())
            .Returns(new BindingConfigurationBuilder<TImplementation>(bindingConfiguration, "ServiceName", mockKernel.Object));
}

然后你可以按如下方式调用方法:

SetupBindAtoB<IAddressService, AddressService>();

在您的方法中,您基本上依赖于允许省略的参数类型的类型推断来指定类型参数本身。通常,此类型推断使方法调用更短。在你的情况下,这只会使它更复杂:

SetupBindAtoB((IAddressService) null, (AddressService) null);

实际上是

的“速记”
SetupBindAtoB<IAddressService, AddressService>(null, null);