简体   繁体   English

如何优化下面的代码

[英]How to optimize the code below

How can I optimize the below code, the below code contains an object array that might have different type of class objects. 如何优化下面的代码,下面的代码包含一个可能具有不同类型的类对象的对象数组。 I would prefer to move to switch case instead of if...else... how could I do it. 我宁愿转移案例而不是if ... else ......我怎么能这样做。

object[] emailObjs;
for (int i = 0; i < emailObjs.Length; i++)
{
if (emailObjs[i] != null)
    {
       if (emailObjs[i] is Rfq)
       {

       }
       else if (emailObjs[i] is RfqBid)
       {

       }
       else if (emailObjs[i] is RfqProjManager)
       {

       }
    }
}

Use C# 7 pattern matching in a switch statement with a type check: 在带有类型检查的switch语句中使用C#7模式匹配

switch (emailObjs[i])
{
    case Rfq r:
        {
            // use r;
            break;
        }
    case RfqBid r:
        {
            // use r;
            break;
        }
}

Although this will compact your code significantly, performance-wise it wouldn't have much benefit over an bunch of if statements, like in your sample code. 虽然这会显着地压缩你的代码,但在性能方面它不会比一堆if语句有很多好处,比如示例代码。

Here is my try: 这是我的尝试:

Rfq, RfqBid, and RfqProjManager implement the same interface. Rfq,RfqBid和RfqProjManager实现相同的接口。 Let's call it IRfq. 我们称之为IRfq。

interface
{
     void DoSomeWork();
}

Then, your for loop could be like this: 然后,你的for循环可能是这样的:

for (int i = 0; i < emailObjs.Length; i++)
{
    if (emailObjs[i] != null && emailObjs is IRfq)
    {
           ((IRfq)emailObjs[i]).DoSomeWork();
    }
}

Is it possible with your design ? 你的设计有可能吗?

Define for all 3 classes common interface with one method: 使用一种方法为所有3个类定义通用接口:

public interface IRfq
{
    void DoSomething();
}

public class Rfq : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

public class RfqBid : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

public class RfqProjManager : IRfq
{
    public void DoSomething()
    {
        //...
    }
}

And you could do just one call in your for loop. 你可以在你的for循环中只做一次调用。

IRfq[] emailObjs;
for (int i = 0; i < emailObjs.Length; i++)
{
   emailObjs[i]?.DoSomething();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM