错误告诉并非所有代码路径都返回一个值

Joy*_*Joy -1 c# return

我写了ac#代码,这对我来说似乎是对的

public static BCSMappedTable GetMappedTable(string p_ListName)
    {
        List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases();
        bool found = false;
        foreach (BCSDataBase connexion in ConnexionList)
        {
            foreach (BCSMappedTable tabList in connexion.GetMappedTables())
            {
                if (tabList.getListeName().Equals(p_ListName))
                {
                    found = true;
                    return tabList;
                }
            }
        }
        if (found)
            return new BCSMappedTable();
    }
Run Code Online (Sandbox Code Playgroud)

但是这个错误不断出现

error : not all code paths return a value
Run Code Online (Sandbox Code Playgroud)

我不知道为什么!我倾斜我总是返回所需的值

Yan*_*eau 7

在函数结束时,如果found为false,则表示没有返回路径...

当你return在循环中有一个语句时,函数会在找到项目后立即退出,因此你不需要found变量.您可以使用以下内容:

public static BCSMappedTable GetMappedTable(string p_ListName)
{
    List<BCSDataBase> ConnexionList = BCSManagement.GetAllDataBases();
    foreach (BCSDataBase connexion in ConnexionList)
    {
        foreach (BCSMappedTable tabList in connexion.GetMappedTables())
        {
            if (tabList.getListeName().Equals(p_ListName))
            {
                // return as soon as the item is found
                return tabList;
            }
        }
    }

    // this code won't be executed if the item was found before...
    return new BCSMappedTable();
}
Run Code Online (Sandbox Code Playgroud)