C#,如何使用处理程序删除复制页面

本文关键字:删除 复制 程序 处理 何使用 | 更新日期: 2023-09-27 18:30:37

请说"如何最佳"重写此代码而不进行复制粘贴。现在我有两个具有等效 lambda 处理程序的处理程序......很抱歉更多的代码和糟糕的风格((

    wc.DownloadStringCompleted += (sender, args) =>
    {
        try
        {
            res = (T)(object)args.Result;
            var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set''-Cookie:''s*([''w''-_''.]+''s*=''s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
            foreach (Match val in cook)
                cookies += val.Groups[1].Value.Trim() + "; ";
            isComplited = true;
        }
        catch (Exception e)
        {
            lastError = e.InnerException.Message;
        }
    };

    wc.UploadDataCompleted += (sender, args) =>
    {
        try
        {
            res = (T)(object)args.Result;
            var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set''-Cookie:''s*([''w''-_''.]+''s*=''s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
            foreach (Match val in cook)
                cookies += val.Groups[1].Value.Trim() + "; ";
            isComplited = true;
        }
        catch (Exception e)
        {
            lastError = e.InnerException.Message;
        }
    };

C#,如何使用处理程序删除复制页面

wc.DownloadStringCompleted += (sender, args) =>
{
    PerformAction(sender,args);
};

wc.UploadDataCompleted += (sender, args) =>
{
    PerformAction(sender,args);
};

或更短:

wc.DownloadStringCompleted += PerformAction;
wc.UploadDataCompleted += PerformAction;

创建包含此代码的新方法并运行它而不是双精度代码

public void PerformAction(object sender, EventArgs args)
{
        try
        {
            res = (T)(object)args.Result;
            var cook = Regex.Matches(wc.ResponseHeaders.ToString(), "Set''-Cookie:''s*([''w''-_''.]+''s*=''s*[^;]+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
            foreach (Match val in cook)
                cookies += val.Groups[1].Value.Trim() + "; ";
            isComplited = true;
        }
        catch (Exception e)
        {
            lastError = e.InnerException.Message;
        }
}