如何用函数分隔我的编码。 [英] How to seperate my coding with functions.

查看:68
本文介绍了如何用函数分隔我的编码。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想要解决以下情况...



我尝试过:



i希望用一个函数分隔以下内容,

want solution for below scenario...

What I have tried:

i want to separate following with one function,

HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);
               myWebRequest.Accept = "image/*";
               myWebRequest.Method = "GET";





然后跟随另一个函数,



And then following with another function,

HttpWebResponse myHttpWebResponse = (HttpWebResponse)myWebRequest.GetResponse(); 
                Response.Clear();
                
                Stream receiveStream = myHttpWebResponse.GetResponseStream();
                Response.ContentType = "image/jpeg";







如果喜欢这两个功能如何分离,那么我如何使用第一个函数中的myWebRequest变量到第二个函数?




if like this two functions separated, then how can i use the "myWebRequest" Variable from the first function into secondly function?

推荐答案

从一个函数返回对象并将其传递给下一个< br $>


Return the object from one function and pass it to the next

public class MyClass
{
    public HttpWebRequest CreateRequest(string url)
    {
        HttpWebRequest myWebRequest = (HttpWebRequest)WebRequest.Create(url);
        myWebRequest.Accept = "image/*";
        myWebRequest.Method = "GET";

        return myWebRequest;
    }

    public void GetResponse(HttpWebRequest request)
    {
        HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
        Response.Clear();

        Stream receiveStream = myHttpWebResponse.GetResponseStream();
        Response.ContentType = "image/jpeg";
    }
}







// calling code
MyClass c = new MyClass();
HttpWebRequest r = c.CreateRequest("http://www.google.com");
c.GetResponse(r);





或者做更多面向对象的事情并将对象保持为内部变量< br $>




Or do things more object-orientated and keep the object as an internal variable

public class MyClass
{
    private HttpWebRequest myWebRequest;

    public void CreateRequest(string url)
    {
        this.myWebRequest = (HttpWebRequest)WebRequest.Create(url);
        myWebRequest.Accept = "image/*";
        myWebRequest.Method = "GET";
    }

    public void GetResponse()
    {
        System.Diagnostics.Debug.Assert(this.myWebRequest != null, "Call CreateRequest before calling GetResponse");

        HttpWebResponse myHttpWebResponse = (HttpWebResponse)this.myWebRequest.GetResponse();
        Response.Clear();

        Stream receiveStream = myHttpWebResponse.GetResponseStream();
        Response.ContentType = "image/jpeg";
    }
}


这篇关于如何用函数分隔我的编码。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆