我有一条if语句,变得有点麻烦。我想知道是否存在更好的方法来处理多个类似的if语句,例如合并为一个语句或使用其他条件语句(例如while或do循环)。任何建议表示赞赏。
WAMP/XAmpp
缺点是,我基本上是在检查对象是否为空,如果不使用扩展方法来确定相似的对象是否相等。 (我没有重写isEquals和getHashCode)。如果该对象为null,则无法调用areEquals扩展方法,因此必须进行检查。
答案 0 :(得分:1)
使用C#6中引入的safe-navigation operator和带有多个条件的单个if
语句,例如:
if (options.OpenCloseOverridesOptions?.AreEqual(OpenCloseOverridesOptions) != true
|| options.DeliveryOpenCloseOverridesOptions?.AreEqual(DeliveryOpenCloseOverridesOptions) != true
|| options.PickupOpenCloseOverridesOptions?.AreEqual(PickupOpenCloseOverridesOptions) != true)
return false;
答案 1 :(得分:1)
尝试一下:
private String getRandomDataFromCategory(String name/* @param for the name of text file*/){
readings = "";
StringBuffer stringBuffer = new StringBuffer();
String[] temp;
try{
//getting file from asset folder
InputStream inputStream = getAssets().open(name + ".txt",AssetManager.ACCESS_BUFFER);
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
inputStream.close();
stringBuffer.append(new String(buffer));
// to check if stringBuffer isn't empty
if (stringBuffer.length() != 0){
//spliting stringBuffer
temp = stringBuffer.toString().split("\\`");
Random random = new Random();
// to create random index of array temp
int a = random.nextInt(temp.length - 1);
readings = temp[a];
}
}catch (Exception e) {
Toast.makeText(gaming.this, e.toString(),Toast.LENGTH_SHORT).show();
}
return readings;
}
答案 2 :(得分:1)
如果您想返回bool
,则可以直接返回条件。
我们可以使用另一种技能(De Morgan's laws)来吧!进入语句,这将颠倒所有逻辑,使代码更清晰。
return
(options.OpenCloseOverridesOptions == null || options.OpenCloseOverridesOptions.AreEqual(OpenCloseOverridesOptions)) &&
(options.DeliveryOpenCloseOverridesOptions == null || options.DeliveryOpenCloseOverridesOptions.AreEqual(DeliveryOpenCloseOverridesOptions)) &&
(options.PickupOpenCloseOverridesOptions == null || options.PickupOpenCloseOverridesOptions.AreEqual(PickupOpenCloseOverridesOptions))&&
(options.PickupServiceWindowOverridesOptions == null || options.PickupServiceWindowOverridesOptions.AreEqual(PickupServiceWindowOverridesOptions) &&
(options.DeliveryServiceWindowOverridesOptions == null || options.DeliveryServiceWindowOverridesOptions.AreEqual(DeliveryServiceWindowOverridesOptions)&&
(options.ServiceWindowOverridesOptions == null || options.ServiceWindowOverridesOptions.AreEqual(ServiceWindowOverridesOptions)&&
(options.LineItemsOptions == null || options.LineItemsOptions.AreEqual(LineItemsOptions)