Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在using语句中使用条件逻辑可以吗_C#_.net_Dependency Injection - Fatal编程技术网

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

C# 在using语句中使用条件逻辑可以吗,c#,.net,dependency-injection,C#,.net,Dependency Injection,好的,假设我需要处理订单。我们过去总是只有一种订单,订单。由于奇怪的情况,我们不得不自己制造喷油器,目前正在使用它: using(DependencyInjector.Inject() .ForType<Order>() .ImplementedBy<InsideOrderProcessor>()) { ... }; 使用(DependencyInjector.injector() .ForType()文件 .ImplementedBy()) { ...

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

using(DependencyInjector.Inject()
    .ForType<Order>()
    .ImplementedBy<InsideOrderProcessor>())
{ ... };
使用(DependencyInjector.injector()
.ForType()文件
.ImplementedBy())
{ ... };
现在我们有了一个新的订单类型或订单,这需要在处理过程中有细微的差异。但它仍然是类型顺序,不能是其他类型。可以这样做吗:

using( isInsideOrder
    ? DependencyInjector.Inject()
        .ForType<Order>()
        .ImplementedyBy<InsideOrderProcessor>()
    : DependencyInjector.Inject()
        .ForType<Order>()
        .ImplementedBy<OutisdeOrderProcessor>()) 
{ ... };
使用(isInsideOrder)
?DependencyInjector.Injection()
.ForType()文件
.ImplementedyBy()
:DependencyInjector.Injection()
.ForType()文件
.ImplementedBy())
{ ... };
这会奏效吗?如果是这样的话,可以这样做吗?

从某种意义上说,代码可以编译,但是它不是特别可读。为了编写易于维护的代码,我建议将其重构为单独的方法。它应该看起来有点像这样:

IOrderProcessor GetOrderProcessor(bool isInsideOrder) 
{
    if (isInsideOrder)
    {
        return DependencyInjector.Inject()
            .ForType<Order>()
            .ImplementedyBy<InsideOrderProcessor>();
    }
    else
    {
        return DependencyInjector.Inject()
            .ForType<Order>()
            .ImplementedBy<OutisdeOrderProcessor>();
    }
}
using(this.GetOrderProcessor(isInsideOrder))
{
    ...
}
从某种意义上讲,代码可以编译,但它不是特别可读。为了编写易于维护的代码,我建议将其重构为单独的方法。它应该看起来有点像这样:

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

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

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

你试过编译代码吗?不幸的是,我有几个小时不在我的个人机器上,所以我不知道。这个想法刚刚在我脑海中闪过,我想在我忘记它之前把它拿出来。你可以,但它会损害可读性。简单地使用一个局部变量,让你的读者感到高兴。你试过编译代码吗?不幸的是,我有几个小时不会在我的个人机器上,所以我不知道。这个想法刚刚在我脑海中闪过,我想在我忘记它之前把它拿出来。你可以,但它会损害可读性。只需使用一个局部变量,就能让你的读者感到高兴。谢谢你的提示。我会尽快试一试的。谢谢你的提示。我会尽快试一试的。