简体   繁体   中英

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.

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 (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.

Here is my try:

Rfq, RfqBid, and RfqProjManager implement the same interface. Let's call it IRfq.

interface
{
     void DoSomeWork();
}

Then, your for loop could be like this:

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:

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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