[英]Multiple equal ifs should return different values from different methods (C#)?
我有一些使用if条件的方法,例如:
string method1()
{
bool x= Convert.ToBoolean(...);
bool y= Convert.ToBoolean(...);
if (x && y)
{
return " ";
}
if (!x && y)
{
return " ";
}
if (!y && x)
{
return " ";
}
if (!x && !y)
{
return "X";
}
return " ";
}
那就是我的第一个方法,现在我有一个类似的方法,它具有相同的检查和相同的布尔值,但是返回其他字符串(不是空格或X)。 解决这个问题的方法是什么?
谢谢
根据您的代码,如果x和y均为假,则仅返回“ X”。 在这种情况下,所有其他组合都应返回“”。 可以将其缩短,但为了便于阅读,我将其保留下来。
method1("X", " ");
method1("OtherValue", " ");
string method1(string matchValue, string nonMatchValue)
{
bool x= Convert.ToBoolean(...);
bool y= Convert.ToBoolean(...);
if (!x && !y)
{
return matchValue;
}
return nonMatchValue;
}
为什么不将所需的返回值作为参数传递给方法?
string method1(string returnVal1, string returnVal2)
{
bool x= Convert.ToBoolean(...);
bool y= Convert.ToBoolean(...);
if (x && y)
{
return returnVal1;
}
if (!x && y)
{
return returnVal1;
}
if (!y && x)
{
return returnVal1;
}
if (!x && !y)
{
return returnVal2;
}
return returnVal1;
}
优雅的方法是重构代码,以便布尔检查位于其他两个方法均可访问的自己的方法中,然后每个方法都可以基于布尔检查的结果返回字符串。
例
private int BinaryTruthTest(bool x, bool y)
{
if(x && y)
{
return 3;
}
if(!x && y)
{
return 1;
}
if(!y && x)
{
return 2;
}
if(!x && !y)
{
return 0;
}
}
string method1()
{
bool x = Convert.ToBoolean(...);
bool y = Convert.ToBoolean(...);
int testResult = BinaryTruthTest(x, y);
if(testResult==0)
{
return "X";
}
else
{
return " ";
}
}
不确定要执行的操作,但是如果您想要该方法的通用版本,而只改变结果,则可以将结果作为二维数组传递。
string method1(string[][] result) {
bool x= Convert.ToBoolean(...);
bool y= Convert.ToBoolean(...);
int u = (x ? 1 : 0);
int v = (y ? 1 : 0);
return result[u][v];
}
这取决于实际问题,但是我怀疑您需要一个可以在任何地方重用的新类:
class DecisionMaker
{
string _both;
string _notX;
string _notY;
string _neither;
string _default;
public DecisionMaker(string both, string notX, string notY, string neither, string defaultVal)
{
_both = both;
_notX = notX;
_notY = notY;
_neither = neither;
_default = defaultVal;
}
public string Method1(bool x, bool y)
{
if (x && y)
return _both;
if (!x && y)
return _notX;
if (!y && x)
return _notY;
if (!x && !y)
return _neither;
return _default;
}
}
或者(可选),您可以在Method1中使用Convert.ToBoolean(...)东西,并使Method1没有参数。 或者,您可以创建带有受保护抽象方法的DecisionMakerBase抽象类,该抽象方法仅允许您更改需要更改的功能。 这确实取决于您的情况。
如果您希望方法二针对四种不同的情况返回四个不同的值,则可以执行以下操作:
string method1(string[] values)
{
if (x && y)
{
return values[0];
}
if (!x && y)
{
return values[1];
}
if (!y && x)
{
return values[2];
}
if (!x && !y)
{
return values[3];
}
}
但是,这不是很漂亮。 此方法在您的应用程序中有什么用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.