函数不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常

函数代码为:

 Function result_ss() As String
        If RadioButton_ss1.Checked = True Then result_ss = "1"
        If RadioButton_ss2.Checked = True Then result_ss = "2"
    End Function

求大神帮忙

 Function result_ss() As String
        If RadioButton_ss1.Checked = True Then result_ss = "1"
        If RadioButton_ss2.Checked = True Then result_ss = "2"
    End Function
        改
        Function result_ss() As String
            result_ss = "";
        If RadioButton_ss1.Checked = True Then result_ss = "1"
        If RadioButton_ss2.Checked = True Then result_ss = "2"
    End Function

提示警告消息:“result_ss”不会在所有代码路径上都返回值。当使用结果时,可能会在运行时发生 null 引用异常。

@danielinbiti的方法,可避免产生这样的问题。
但是这样的问题根本原因在于你的判断没有覆盖所有的情况。
因此,一般来说用if 。。。 else if 。。。 else 。。。 end if来保证所有情况都得到覆盖。

Function result_ss() As String
        If RadioButton_ss1.Checked = True Then 
                    result_ss = "1"
                Else If RadioButton_ss2.Checked = True Then 
                    result_ss = "2"
                Else
                    result_ss = ""
                End If
    End Function

只有两个if语句,如果两个if都不成立呢,这种情况并没有覆盖。应该给予处理。

1.可以if-else语句完整使用。
2.可以只是用if语句,最后补上一句return null;之类的。

if(){ return "1";}
if(){ return "2";}

return null;