在 using 语句中使用条件逻辑可以吗

is it ok to use conditional logic inside a using statement

好的,假设我需要处理一个订单。我们过去总是只有一种订单,订单。由于奇怪的情况,我们不得不自己制作注射器,目前正在使用它:

using(DependencyInjector.Inject()
    .ForType<Order>()
    .ImplementedBy<InsideOrderProcessor>())
{ ... };

现在我们有一个新的订单类型或订单,需要在处理上有细微的差别。但它仍然是 Order 类型,不能是其他类型。可以做类似的事情吗:

using( isInsideOrder
    ? DependencyInjector.Inject()
        .ForType<Order>()
        .ImplementedyBy<InsideOrderProcessor>()
    : DependencyInjector.Inject()
        .ForType<Order>()
        .ImplementedBy<OutisdeOrderProcessor>()) 
{ ... };

这还能用吗?如果可以,可以吗?

还可以,因为代码可以编译,但可读性不是特别好。为了编写易于维护的代码,我建议将其重构为一个单独的方法。它看起来应该有点像这样:

IOrderProcessor GetOrderProcessor(bool isInsideOrder) 
{
    if (isInsideOrder)
    {
        return DependencyInjector.Inject()
            .ForType<Order>()
            .ImplementedyBy<InsideOrderProcessor>();
    }
    else
    {
        return DependencyInjector.Inject()
            .ForType<Order>()
            .ImplementedBy<OutisdeOrderProcessor>();
    }
}

然后你可以这样写你的using

using(this.GetOrderProcessor(isInsideOrder))
{
    ...
}

在 using 块之外创建对象(通过您喜欢的任何方式)然后在 using 块中使用它是可以接受的。换句话说,它不需要在 using 块中实例化以在 using 块中使用它。