我打算做一个复杂的数字类,我似乎有太多的条件涉及我的一个函数上的多个语句。以下是我的程序片段,其中包含ToString()
函数:
public override string ToString()
{
if (this.real == 0 && this.imaginary == 0)
{
return "0";
}
else if (this.real == 0 && this.imaginary == 1)
{
return "i";
}
else if (this.real == 0 && this.imaginary == -1)
{
return "-i";
}
else if (this.real == 0 && (this.imaginary != 1 && this.imaginary != -1))
{
return String.Concat(this.imaginary.ToString(), "i");
}
else if (this.real != 0 && this.imaginary == 0)
{
return String.Concat(this.real.ToString());
}
else if (this.real != 0 && this.imaginary == 1)
{
return String.Concat(this.real.ToString(), " + i");
}
else if (this.real != 0 && this.imaginary == -1)
{
return String.Concat(this.real.ToString(), " - i");
}
else if (this.real != 0 && this.imaginary < -1)
{
this.imaginary = -this.imaginary;
return String.Concat(this.real.ToString(), " - ", this.imaginary.ToString(), "i");
}
return String.Concat(this.real.ToString(), " + ", this.imaginary.ToString(), "i");
}
switch
语句会对多种情况有所帮助吗?
答案 0 :(得分:3)
通过消除冗余检查,使代码更具可读性。
使用字符串插值代替String.Concat
public override string ToString()
{
if (real == 0)
{
if (imaginary == 0)
{
return "0";
}
if (imaginary == 1)
{
return "i";
}
if (imaginary == -1)
{
return "-i";
}
if (imaginary != 1)
{
return $"{imaginary}i";
}
}
else
{
if (imaginary == 0)
{
return real.ToString();
}
if (imaginary == 1)
{
return $"{real} + i";
}
if (imaginary == -1)
{
return $"{real} - i";
}
if (imaginary < -1)
{
imaginary = -imaginary;
return $"{real} - {imaginary}i";
}
}
return $"{real} + {imaginary}i";
}
答案 1 :(得分:1)
this.real
中不能有多个条件,但看起来this.imaginary
只有两种可能性,0或1,所以你可以把它用作{{1}的开关}。
最好使用String.Format()
或字符串插值而不是String.Concat()
。
public override string ToString() {
if (this.real == 0) {
switch(this.imaginary) {
case 0:
return "0";
case 1:
return "i";
case -1:
return "-i";
default:
return $"{this.imaginary}i";
}
else {
switch(this.imaginary) {
case 0:
return this.real.ToString();
case 1:
return $"{this.real} + i";
case -1:
return $"{this.real} - i";
default:
if (this.imaginary < -1) {
this.imaginary = -this.imaginary;
return $"{this.real} - {this.imaginary}i";
}
}
}
return $"{this.real} + {this.imaginary}i";
}
答案 2 :(得分:0)
您的代码过于复杂且冗余,因为您已针对每种可能的情况提出单独的分支。如果您将其分解并执行以下操作,您的代码将更加简单:
以下将执行此操作:
private string RealPartString()
{
if (real == 0) { return imaginary == 0 ? "0" : null; }
return real.ToString();
}
private string ImaginaryPartString()
{
if (imaginary == 0) { return null; }
var abs = Math.Abs(imaginary);
var number = abs == 1 ? "" : abs.ToString();
// Only include the sign here if there is no real part
var sign = real == 0 && imaginary < 0 ? "-" : "";
return sign + number + "i";
}
public override string ToString()
{
var parts = new[] { RealPartString(), ImaginaryPartString() }.Where(s => s != null);
var sign = imaginary < 0 ? " - " : " + ";
return string.Join(sign, parts);
}