The*_*ner 0 c# methods extension-methods if-statement return
假设我有以下扩展方法:
public static string sampleMethod(this int num) {
return "Valid";
}
Run Code Online (Sandbox Code Playgroud)
如何终止sampleMethod并显示消息框num > 25?
如果我尝试下面的代码,我会收到一个红色下划线sampleMethod并说not all code path returns a value.
public static string sampleMethod(this int num) {
if(num > 25) {
MessageBox.Show("Integer must not exceed 25 !");
} else {
return "Valid String";
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想补充throw new Exception("...");下MessageBox.Show,一切顺利,但在应用程序终止.
如果不满足条件,如何显示MessageBox并终止方法?
谢谢.
确保始终将string(因为字符串是您的返回值)返回到函数的所有可能结果/路径
public static string sampleMethod(this int num) {
if(num > 25) {
MessageBox.Show("Integer must not exceed 25 !");
return "";
}
return "Valid String";
}
Run Code Online (Sandbox Code Playgroud)
你的代码不起作用,因为
public static string sampleMethod(this int num) {
if(num > 25) {
MessageBox.Show("Integer must not exceed 25 !");
// when it go to this block, it is not returning anything
} else {
return "Valid String";
}
}
Run Code Online (Sandbox Code Playgroud)