c# - 将非实例化的类和接口(interface)传递给泛型方法

标签 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 的真实对象?

最佳答案

你试过这个吗?

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>();

关于c# - 将非实例化的类和接口(interface)传递给泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50164631/

相关文章:

c# - 如何获取列表中项目的重新出现次数? (没有不可变循环)

javascript - typescript |从对象 T 中提取具有类型 K 值的所有键名

c# - 效率 : Func<T>, 与 T 的实例

java - 使用作为参数传递的类实例化泛型类型

vb.net - 为什么不能将 IView(Of SpecificViewModel) 转换为 IView(Of ViewModelBase)?

c# - 如何编辑 gpedit 政策

c# - 如何在编写和读取xml时检测段落并在页面上正确显示?

c# - 如何在 MVC.NET 中加载前 x 个项目并为用户提供加载更多项目的选项

c# - 什么时候使用 NotSupportedException 不好?

c# - 由于 "does not have the matching return type"错误,泛型类型的接口(interface)实现失败