C# 在不使用“if”的情况下执行此操作 | if(s == "value1"){...} else if(s == "value2") { ...}

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1999282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:32:14  来源:igfitidea点击:

do this without using an "if" | if(s == "value1"){...} else if(s == "value2") { ...}

javac#

提问by Omu

According to anti-if campaignit is a best practice not to use ifs in our code. Can anyone tell me if it possible to get rid of the if in this piece of code ? (switch is also not an option, The point is to remove the conditional logic, not replace ifs with similar language constructs)

根据反 if 活动,最好不要在我们的代码中使用if。谁能告诉我是否有可能摆脱这段代码中的 if ?(switch 也不是一个选项,重点是去掉条件逻辑,而不是用类似的语言结构替换 ifs

if(s == "foo")
{
    Writeln("some logic here");
}
else if(s == "bar")
{
    Writeln("something else here");
}
else if(s == "raboof")
{
    Writeln("of course I need more than just Writeln");
}

(language: Java or C#)

(语言:Java 或 C#)

采纳答案by BalusC

Make use of the strategy pattern.

利用策略模式

In Java terms:

在 Java 术语中:

public interface Strategy {
    void execute();
}

public class SomeStrategy implements Strategy {
    public void execute() {
        System.out.println("Some logic.");
    }
}

which you use as follows:

您使用如下:

Map<String, Strategy> strategies = new HashMap<String, Strategy>();
strategies.put("strategyName1", new SomeStrategy1());
strategies.put("strategyName2", new SomeStrategy2());
strategies.put("strategyName3", new SomeStrategy3());

// ...

strategies.get(s).execute();

回答by serhio

First of all, be very attentivewhen reading such "anti" campaigns.

首先,阅读此类“反”运动时要非常专心

  • Ask yourself if Anti IFcampaign would like eliminate the logicin the applications?!
  • The ideas could have a good application in onesituation and a stupid in another one. Be reasonable.
  • It may be possible that multipleusage of IFmay encumber the reader of the code. but this is anyreason to eliminate the iffrom your code, more that than, this is almost impossible.
  • By the way anywhere in the MS design guidelines is indicated do not use if(like is done, by e.g. for the gotostatement usage of witch is not recommended)...
  • 问问自己Anti IF活动是否想要消除应用程序中的逻辑?!
  • 这些想法在一种情况下可以很好地应用,而在另一种情况下却很愚蠢。讲道理。
  • 有可能的是多个的使用IF可能妨碍代码的读取器。但这是从代码中消除if 的任何理由,更多的是,这几乎是不可能的。
  • 顺便说一下,MS 设计指南中的任何地方都表明不要使用if(就像已经完成的那样,例如,不推荐使用 witch的goto语句)...

C#

C#

    switch (myStringVar)
    {
        case "one": doSomething();  break;
        case "two": doSomething(); break;
        case "three": doSomething(); break;
        default: doSomething(); break;
    }

Finally, it reduces this code to the ifs... so, only for readability is better, not for performance.

最后,它将这段代码简化为ifs... 所以,只是为了可读性更好,而不是为了性能。

Actually, if Microsoft believes that switch (in c#) is better to replace with if's - OK, I will use (in the concrete situation that you described) the switch.

实际上,如果微软认为 switch (在 c# 中)最好用 if 替换 - 好的,我将使用(在你描述的具体情况下)switch

By the way, it seems that the campaign responds to your question very clear in this example

顺便说一句,在此示例中,该活动似乎非常清楚地回答了您的问题

回答by ufukgun

write classes with virtual methods which is derived from your abstract base class SomeThingWriter.

使用从抽象基类 SomeThingWriter 派生的虚拟方法编写类。

then every class which are derived from base class should implement a function like writeSomething or whatever you want.

那么从基类派生的每个类都应该实现一个函数,比如 writeSomething 或任何你想要的。

abstract class MyBaseClass
{
     public abstract void writeSomething();
}

class DerivedClass1 : MyBaseClass
{
    public override void writeSomething()
    {
        Writeln("something else here  1");
    }
}

class DerivedClass2 : MyBaseClass
{
    public override void writeSomething()
    {
        Writeln("something else here  2");
    }
}

than just call like

不仅仅是打电话

MyBaseClass c = new DeriveClass1();
c.writeSomething();
c = new DerivedClass2();
c.writeSomething();

回答by bmargulies

Make an associative data structure. Map<String, String>in Java, IDictionary<string, string>in C#. Initialize it at the beginning of time, and then ...

制作关联数据结构。Map<String, String>在 Java 中,IDictionary<string, string>在 C# 中。在开始的时候初始化它,然后...

回答by Peter

In some cases it might be legit to avoid the if structure

在某些情况下,避免 if 结构可能是合法的

in others its just plain idiocy to try to avoid if.

在其他人中,如果试图避免,那只是简单的白痴。

While the examples provided to avoid the if structure are valid alternatives you should ask yourself this:

虽然提供的避免 if 结构的示例是有效的替代方案,但您应该问自己:

Why am i making my code unnecessarly complicated to avoid a simple if structure ? If the only reason is that you have to because of the anti-if campaign then its bad reason

为什么我让我的代码不必要地复杂以避免简单的 if 结构?如果唯一的原因是因为反 if 活动而必须这样做,那么它的坏理由

回答by glmxndr

Java

爪哇

Use an enum which implements a certain method.

使用实现某种方法的枚举。

enum MyEnum{

    foo{
        public void mymethod(String param1, String param2){
            //dostuff...
        }
    },

    bar{
        public void mymethod(String param1, String param2){
            //dostuff...
        }
    };

    public abstract void mymethod(String param1, String param2);
}

Then in your class :

然后在你的课上:

MyEnum.valueOf(mystring).mymethod(param1, param2);

回答by Draemon

Looking at the campaign, it's very poorly explained. There's nothing wrong with ifs, but in certain casesthey can indicate that you're not using OOP to its full potential.

看看这个活动,它的解释很差。ifs 没有任何问题,但在某些情况下,它们可能表明您没有充分发挥 OOP 的潜力。

What the campaign is trying to promote is increased use of polymorphism in order to decouple calling code from the type of object it is looking at.

该活动试图推广的是增加多态性的使用,以便将调用代码与其正在查看的对象类型分离。

You would use some smarter object instead of s being a string:

您将使用一些更智能的对象而不是 s 作为字符串:

interface I {
  public String getName();
  public void doSomething();
}

class A implements I {
  public String getName() { return "one"; }
  public void doSomething() { ...; }
}

class B implements I {
  public String getName() { return "two"; }
  public void doSomething() { ...; }
}

Then you can replace the ifs with:

然后,您可以将 ifs 替换为:

I obj = ...get an A or B from somewhere...;
obj.doSomething();

回答by cletus

Here's one way... :)

这是一种方法... :)

delegate void DoStuff();

...

IDictionary<string, DoStuff> dict = new Dictionary<string, DoStuff>();
dict["foo"] = delegate { Console.WriteLine("some logic here"); };
dict["bar"] = delegate { Console.WriteLine("something else here"); };
dict["raboof"] = delegate { Console.WriteLine("of course I need more than just Writeln"); };
dict["foo"]();

回答by Syed M Shaaf

I don't think you are making a fair comparison here.

我不认为你在这里进行公平的比较。

From the look of it the Anti-if campaign is just about practicing a better design approach.

从它的外观来看,Anti-if 活动只是为了实践更好的设计方法。

However in your case you can see from all the above examples that if can not be removed from the surface and will always exist somewhere down in the center.

但是,在您的情况下,您可以从上述所有示例中看到,如果无法从表面移除,并且将始终存在于中心下方的某处。

And why exactly is that?

为什么会这样?

Well If is a general purpose of life. I don't mean to say start coding if every where but in general without if there is no differentiation, if brings decisions and purpose, if that wasn't there then every object in the world would just execute as its suppose to without even knowing anything other then it self. And very simple you wouldn't have asked this question. :)

好吧,如果是生活的一般目的。我并不是说如果每个地方都开始编码,但总的来说,如果没有差异,如果带来决定和目的,如果不存在,那么世界上的每个对象都将按照其假设执行,甚至不知道任何其他然后它自己。很简单,你不会问这个问题。:)

回答by Pankaj

I think you are looking for Factory Patterns.

我认为您正在寻找Factory Patterns