2

请说一下“如何优化”重写此代码而无需复制粘贴。现在我有两个具有等效 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;
        }
    };
4

1 回答 1

3
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;
        }
}
于 2013-09-09T12:13:34.943 回答