繁体   English   中英

此功能有什么问题。 无法返回字符串值

[英]What's wrong with this function. unable to return string value

public static string GetContentFromSPList(string cValueToFind)
{   
    string cValueFound = "";
    try
    {
        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (SPSite site = new SPSite("http://mysite"))
            {
                site.AllowUnsafeUpdates = true;
                using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;

                    SPList oListAbout = web.Lists["About"];
                    SPQuery oQuery = new SPQuery();

                    oQuery.Query = "<OrderBy><FieldRef Name='myField' /></OrderBy><Where><Eq><FieldRef Name='myField' /><Value Type='Choice'>" + cValueToFind + "</Value></Eq></Where>";

                    SPListItemCollection collListItems = oListAbout.GetItems(oQuery);

                    foreach (SPListItem oListItem in collListItems)
                    {
                        cValueFound = (oListItem["FieldContents"] != null ? oListItem["FieldContents"].ToString() : "");
                    }
                }
            }
            return cValueFound;
        });
        //return cValueFound;
    }
    catch (Exception ex)
    {
    }
    finally
    {
        //return cValueFound;
    }
}

以上是一段代码。

问题是不允许返回字符串。 它不断给出编译错误。 我确定我做错了!!

谢谢。

是这样的:

“并非所有代码都返回值”。

如果是这样,只需添加

public static string GetContentFromSPList(string cValueToFind)
{   
       string cValueFound = "";
        try
        {
           //code
        }
        catch (Exception ex)
        {
        }
        finally
        {
           //some cleanup
        }

        return cValueFound ;
 }

将其放在方法的底部,因为如果捕获到异常,则不会返回。

    catch (Exception ex)
    {
        return cValueFound;
    }
    finally
    {
    }
}

你不能从finally回来,
control cannot leave the body from finally clause或其他内容control cannot leave the body from finally clause

最终或从捕获后移回收益

只需在finally块下面添加return语句即可。

不要尝试尝试返回。

我已经看到开发人员错过了很多次。 发生这种情况的原因是,一旦定义了函数的返回类型,则函数应该在所有出口处都具有return语句。 在这种情况下,一个函数应该在try块的末尾有一个return语句,在catch块内部有一个return语句,或者在Tigran定义的底部只有一个右语句。 如果您不打算从catch块返回任何东西,则只需返回null;否则,返回null。

public static string GetContentFromSPList(string cValueToFind)
{   
       string value= "";
        try
        {
           //code
return value;
        }
        catch (Exception ex)
        {
return null;
        }
        finally
        {
           //some cleanup
        }


 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM