C# - 并非所有代码路径 return 一个值

C# - Not all code paths return a value

抱歉,它与其他帖子类似,但我已经阅读了一个小时的类似帖子,reviewed/re-reviewed 我的代码,但我只是看不到它没有 return 值的地方。任何帮助表示赞赏。

public static bool UploadLog()
        {
            var uploader = new BackgroundWorker();
            uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
            {
                Properties.Settings.Default.logUrl = "";
                Properties.Settings.Default.Save();

                System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
                Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
                Data["api_paste_expire_Date"] = "N";
                Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + @"\Logs\RWC.log");
                Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
                Data["api_option"] = "paste";

                WebClient wb = Proxy.setProxy();

                try
                {
                    byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
                    string response;
                    using (MemoryStream ms = new MemoryStream(bytes))
                    using (StreamReader reader = new StreamReader(ms))
                        response = reader.ReadToEnd();

                    if (response.StartsWith("Bad API request"))
                    {
                        Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
                        e.Result = false;
                    }
                    else 
                    {
                        Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
                        Properties.Settings.Default.logUrl = response;
                        Properties.Settings.Default.Save();
                        e.Result = true;
                    }
                }
                catch (Exception ex)
                {
                    Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
                    e.Result = false;
                }
            };
            uploader.RunWorkerAsync();
        }

编辑: 我已经尝试 运行 这个函数作为 async 但它导致锁定 UI,因此 运行 这在后台工作人员中。

对于 return 一个 bool 的函数(参见函数定义),您必须至少在代码中的某处 return 一个。在 uploader.RunWorkerAsync (); 之后添加 return true;。这将完成这项工作。

更好的可能性是使函数 async 或使用 void 作为 return 类型。

你的方法声明声明了一个 bool return 值。 public static bool UploadLog(),因此,您的所有代码路径都必须 return 一个布尔值。通过代码路径....您的方法的所有 "exit points" 都必须 return 一个值。除非您将 "bool" 更改为 "void",这仅仅意味着您的方法没有 return 值。

    /// <summary>
    /// With return bool
    /// </summary>
    /// <returns></returns>
    public static bool UploadLog()
    {
        var didItWork = true;//here's a return value you could use. Initialize to true

        var uploader = new BackgroundWorker();
        uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
        {
            Properties.Settings.Default.logUrl = "";
            Properties.Settings.Default.Save();

            System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
            Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
            Data["api_paste_expire_Date"] = "N";
            Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + @"\Logs\RWC.log");
            Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
            Data["api_option"] = "paste";

            WebClient wb = Proxy.setProxy();

            try
            {
                byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
                string response;
                using (MemoryStream ms = new MemoryStream(bytes))
                using (StreamReader reader = new StreamReader(ms))
                    response = reader.ReadToEnd();

                if (response.StartsWith("Bad API request"))
                {
                    Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
                    e.Result = false;
                }
                else
                {
                    Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
                    Properties.Settings.Default.logUrl = response;
                    Properties.Settings.Default.Save();
                    e.Result = true;
                }
            }
            catch (Exception ex)
            {
                Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
                e.Result = false;
                didItWork = false;//did not work, so set the return value accordingly
            }
        };
        uploader.RunWorkerAsync();

        return didItWork;//return the result

    }

    /// <summary>
    /// Drop the return value by making it void instead of bool
    /// </summary>
    public static void UploadLog()
    {
        var uploader = new BackgroundWorker();
        uploader.DoWork += delegate (object sender, DoWorkEventArgs e)
        {
            Properties.Settings.Default.logUrl = "";
            Properties.Settings.Default.Save();

            System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
            Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
            Data["api_paste_expire_Date"] = "N";
            Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + @"\Logs\RWC.log");
            Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
            Data["api_option"] = "paste";

            WebClient wb = Proxy.setProxy();

            try
            {
                byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
                string response;
                using (MemoryStream ms = new MemoryStream(bytes))
                using (StreamReader reader = new StreamReader(ms))
                    response = reader.ReadToEnd();

                if (response.StartsWith("Bad API request"))
                {
                    Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
                    e.Result = false;
                }
                else
                {
                    Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
                    Properties.Settings.Default.logUrl = response;
                    Properties.Settings.Default.Save();
                    e.Result = true;
                }
            }
            catch (Exception ex)
            {
                Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
                e.Result = false;
                didItWork = false;//did not work, so set the return value accordingly
            }
        };
        uploader.RunWorkerAsync();
    }

一些评论指出使用 async 而不是后台工作者。我对此进行了更多阅读并重新访问了我的代码,它现在可以成功运行,并且也没有锁定 UI 。 :)

我现在的工作代码:

public static async Task<bool> UploadLog()
        {
            Properties.Settings.Default.logUrl = "";
            Properties.Settings.Default.Save();

            System.Collections.Specialized.NameValueCollection Data = new System.Collections.Specialized.NameValueCollection();
            Data["api_paste_name"] = "RWC_Log_" + DateTime.Now.ToString() + ".log";
            Data["api_paste_expire_Date"] = "N";
            Data["api_paste_code"] = File.ReadAllText(Properties.Settings.Default.AppDataPath + @"\Logs\RWC.log");
            Data["api_dev_key"] = "017c00e3a11ee8c70499c1f4b6b933f0";
            Data["api_option"] = "paste";

            WebClient wb = Proxy.setProxy();

            try
            {
                byte[] bytes = wb.UploadValues("http://pastebin.com/api/api_post.php", Data);
                string response;
                using (MemoryStream ms = new MemoryStream(bytes))
                using (StreamReader reader = new StreamReader(ms))
                    response = reader.ReadToEnd();

                if (response.StartsWith("Bad API request"))
                {
                    Logging.LogMessageToFile("Failed to upload log to Pastebin: " + response);
                    return false;

                }
                else 
                {
                    Logging.LogMessageToFile("Logfile successfully uploaded to Pastebin: " + response);
                    Properties.Settings.Default.logUrl = response;
                    Properties.Settings.Default.Save();
                    return true;

                }
            }
            catch (Exception ex)
            {
                Logging.LogMessageToFile("Error uploading logfile to Pastebin: " + ex.Message);
                return true;

            }
        }

我的按钮调用代码:

private async void btnUpload_Click(object sender, EventArgs e)
        {
            this.btnUpload.Enabled = false;
            this.btnUpload.Text = "Uploading...";

            var uploaded = await Task.Run(Pastebin.UploadLog);

            this.btnUpload.Text = "Upload";
            this.btnUpload.Enabled = true;

            if (uploaded == true)
            {
                Clipboard.SetText(Properties.Settings.Default.logUrl);
                MessageBox.Show("Your logfile has been uploaded to Pastebin successfully.\r\n" +
                    "The URL to the Paste has been copied to your clipboard.", "Upload successful!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("The upload of your logfile to Pastebin failed.", "Upload failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }