我有这个方法:
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle) {
}
我尝试执行以下操作:如果hayStack1
和hayStack2
都是null
,则该方法应返回true
,如果其中一个不是null
needle
true
应该null
返回needle
,如果它们都不是true
log4net
可以是其中任何一个或两者都是 protected internal void Handle<T>(T exception)
{
try
{
MessageBox.Show((exception as Exception)?.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
Logger.Error((exception as Exception)?.Message, exception as Exception);
}
catch (Exception ex)
{
Logger.Error($"ErrorHandler (Handle<T>) throws exception {ex.Message}");
Logger.Error("$^", ex);
MessageBox.Show(ex.Message);
}
}
是try
{
...
}
catch (Exception ex)
{
ErrorHandler.Handle(ex);
}
。
我可以这样做,但我的方法非常混乱,有没有办法以优雅的方式做到这一点?
答案 0 :(得分:2)
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle)
{
bool? s1 = hayStack1?.Contains(needle);
bool? s2 = hayStack2?.Contains(needle);
if (s1 ?? s2 ?? true) return true;
return s2 == true;
}
说明:
if (s1 ?? s2 ?? true)
只有在以下情况下才会成立:
s1 == s2 == null
或s1 == true || (s1 == null && s2 == true)
return s2 == true;
由于s1
可能会变为假,我们会检查s2
是否为真。
可以用单个return语句替换。
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle)
{
bool? s1 = hayStack1?.Contains(needle);
bool? s2 = hayStack2?.Contains(needle);
return (s1 ?? s2 ?? true) || s2 == true;
}
答案 1 :(得分:1)
bool CheckIfAvailable(HashSet<int> hayStack1, HashSet<int> hayStack2, int needle)
{
bool setsAreNull = hayStack1 == null && hayStack2 == null;
bool hayStack1ContainsNeedle = hayStack1 != null && hayStack1.Contains(needle);
bool hayStack2ContainsNeedle = hayStack2 != null && hayStack2.Contains(needle);
return setsAreNull || hayStack1ContainsNeedle || hayStack2ContainsNeedle ;
}
或者
[HttpPost]
public HttpResponseMessage CreateEmpAttandance(string value)
{
if (value != "1234")
{
string json = @"{ data: 'Emp Code is not valid.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
else
{
string json = @"{ data: 'data save sucessfully.'}";
var jObject = JObject.Parse(json);
var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jObject.ToString(), System.Text.Encoding.UTF8, "application/json");
return response;
}
}