我刚用曼尼的箱子和开关写了一个程序。那么,在C#中,有什么方法可以避免出现这种情况和切换吗?从我的观点来看,我最终得到了一个“杂乱无章”的程序。所有其他高级全栈开发人员,他们说它是好的,等等。
但基本上我只是好奇你对这个话题的看法?你知道有什么更好的方法来做智能编码没有情况和开关吗?
基本上,这是我的天性,质疑事物的现状.
发布于 2016-12-12 09:35:04
您可以尝试使用类的继承。开关意味着你需要用不同的值做一些类似的事情。希望,下面的例子可以帮助理解我的想法:
public enum SexTypes { Unknown, Male, Female }
public abstract class Human
{
protected string HelloMessage = "common message part";
public abstract SexTypes Sex { get; }
public void SayHello() => Console.WriteLine(HelloMessage); //good way
public void SayHelloWithSwitch() //bad way
{
switch(Sex)
{
case SexTypes.Unknown:
Console.WriteLine(HelloMessage);
break;
case SexTypes.Male:
Console.WriteLine(HelloMessage + " some modifications");
break;
case SexTypes.Female:
Console.WriteLine("new other message");
break;
default:
throw new ArgumentOutOfRangeException();
}
}
}
public class Boy : Human
{
public override SexTypes Sex => SexTypes.Male;
protected new string HelloMessage => base.HelloMessage += " , some message modifications";
}
public class Girl : Human
{
public override SexTypes Sex => SexTypes.Female;
protected new string HelloMessage = "overwrite all message";
}https://stackoverflow.com/questions/41097485
复制相似问题