我尝试使用short-hand重写此方法if:
public string checkInputParamters(string baseUrl, string owner, string documentId, string user, string secret, string type)
{
if (String.IsNullOrEmpty(baseUrl))
return ExceptionsCodes.BASE_URL_CANNOT_BE_NULL_OR_EMPTY.ToString("g");
if (String.IsNullOrEmpty(owner))
return ExceptionsCodes.OWNER_CANNOT_BE_NULL_OR_EMPTY.ToString("g");
return "";
}
我不能这样做,因为返回强迫我在“:”iso“;”之后加上一个值。
public string checkInputParamters(string baseUrl, string owner, string documentId, string user, string secret, string type)
{
return ((null == baseUrl) || (string.Empty == baseUrl)) ? ExceptionsCodes.BASE_URL_CANNOT_BE_NULL_OR_EMPTY.ToString("g");
return ((null == owner) || (string.Empty == owner)) ? ExceptionsCodes.OWNER_CANNOT_BE_NULL_OR_EMPTY.ToString("g");
}
有什么想法吗?
答案 0 :(得分:8)
需要注意的另一件事是你可以替换
((null == owner) || (string.Empty == owner))
与
String.IsNullOrEmpty(owner)
答案 1 :(得分:8)
return String.IsNullOrEmpty(baseUrl)
? YourBaseUrlException
: String.IsNullOrEmpty(owner)
? YourOwnerException
: "";
答案 2 :(得分:0)
如果不是这两种情况之一,则缺少默认返回。
例如:
return String.IsNullOrEmpty(owner)?ExceptionsCodes.OWNER_BLAH.ToString("g"):(String.IsNullOrEmpty(baseUrl)?ExceptionsCodes.BASEURL_BLAH.ToString("g"):"");
答案 3 :(得分:0)
这是你的想法吗?
public string checkInputParamters(string baseUrl, string owner, string documentId, string user, string secret, string type)
{
return String.IsNullOrEmpty(baseUrl) ?
ExceptionsCodes.BASE_URL_CANNOT_BE_NULL_OR_EMPTY.ToString("g") :
( String.IsNullOrEmpty(owner) ? ExceptionsCodes.OWNER_CANNOT_BE_NULL_OR_EMPTY.ToString("g") : "" );
}
答案 4 :(得分:0)
该方法必须返回一些东西。我怀疑最好的例子编译。 (我看到你现在改变它了。)
结合其他两个答案。
public string checkInputParamters(string baseUrl, string owner, string documentId, string user, string secret, string type)
{
return String.IsNullOrEmpty(baseUrl) ?
ExceptionsCodes.BASE_URL_CANNOT_BE_NULL_OR_EMPTY.ToString("g")
: (String.IsNullOrEmpty(owner) ?
ExceptionsCodes.OWNER_CANNOT_BE_NULL_OR_EMPTY.ToString("g")
: String.Empty;
}
答案 5 :(得分:0)
imo,在这种情况下,使用第一个示例布局的解决方案更具可读性。我会更关注这里的可读性,而不是尝试code-golf你的代码。
在String.IsNullOrEmpty(owner)
交换的僵尸解决方案将是一个很好的增强。
答案 6 :(得分:0)
我个人不喜欢内联,但这应该可以解决问题
return (
String.IsNullOrEmpty(baseUrl)?
ExceptionsCodes.BASE_URL_CANNOT_BE_NULL_OR_EMPTY.ToString("g"):(
String.IsNullOrEmpty(owner)?
ExceptionsCodes.OWNER_CANNOT_BE_NULL_OR_EMPTY.ToString("g"):
string.Empty
)
);
几乎和其他人说的一样,我只想在内联ifs中清楚地看到(隐含的)()