2017-02-16 37 views
-2

在程序中,調用名爲HandleHttpRequest的方法,該方法接受HttpContext類的參數。爲什麼我們可以從作爲值傳遞給方法的參數獲取更新結果?

HandleHttpRequest處理httpContext.Request中的傳入請求並寫入對httpContext.Response的響應。

我的問題是爲什麼在撥打HandleHttpRequest完成後,程序可以獲得寫入httpContext.Response的響應?

httpContext作爲值傳遞給HandleHttpRequest,而不是引用,是否正確?

謝謝。

HttpRequest httpRequest = new HttpRequest("", "http://localhost/my.ashx", "timestamp=20170216"); 
MemoryStream memoryStream = new MemoryStream(); 
TextWriter textWriter = new StreamWriter(memoryStream); 
HttpResponse httpResponse = new HttpResponse(textWriter); 
HttpContext httpContext = new HttpContext(httpRequest, httpResponse); 

HandleHttpRequest(httpContext); 

textWriter.Flush(); 
byte[] buffer = memoryStream.GetBuffer(); 

HandleHttpRequest簽名是

public void HandleHttpRequest(HttpContext context) 

所以它的參數是不是一個參考。

+0

'httpContext'通過值傳遞,但它是對的'實例的引用HttpContext'所以如果它通過'HandleHttpRequest'中的共享引用進行變異,所做的更改將可見。 – Lee

+0

您正將*參考*的值傳遞給'httpContext'的一個實例。用簡單的英語,你傳入一個對'HttpContext'實例的引用。這個方法不是爲了創建一個克隆,而是爲了'HttpContext'的那個實例。 –

+0

*「是否將httpContext作爲HandleHttpRequest的值傳遞給HandleHttpRequest,而不是引用,是否正確?」 - 顯然,這是不正確的,因爲您所看到的行爲無疑是與您在同一個實例上運行的方法,而不是複製。誰告訴你'HandleHttpRequest'獲得'httpContext'的副本,爲什麼你暫時相信它可能是真的? –

回答

1

將httpContext作爲值傳遞給HandleHttpRequest而不是引用,是否正確?

httpContext變量是對HttpContext的實例的引用。引用被傳遞給方法,所以方法返回後,方法所做的任何事情都會顯示出來。但請記住,引用變量是通過值傳遞給方法的,所以方法不能爲其分配另一個引用。

這裏是一個小應用程序,這將澄清一些混亂:

internal class Program { 

    private static void Main(string[] args) { 

     var p1 = new Person { Name = "George" }; 
     ChangeName(p1); 

     // This will have "George" because the method never operated 
     // on the person passed to it. 
     var name = p1.Name; 

     // Now we call this method which will change the name of the person 
     // we are passing to it. 
     ChangeName2(p1); 

     // Therefore, now it will have "Jerry" 
     var name2 = p1.Name; 

     var p2 = new Person { Name = "Kramer" }; 

     // Let's record this so we can compare it later 
     var p2Before = p2; 

     // Now we do the exact same thing we did when we passed by value, 
     // but now we pass by ref. 
     ChangeName(ref p2); 

     // This will have "Smith" 
     var name3 = p2.Name; 

     // This will return false; 
     var samePerson = p2 == p2Before; 

     Console.Read(); 
    } 

    public static void ChangeName(Person person) { 
     // This is a whole new person 
     var p = new Person() { Name = "Smith" }; 
     person = p; 
    } 

    public static void ChangeName2(Person person) { 
     person.Name = "Jerry"; 
    } 

    // This takes the reference and assigns a new person to the reference 
    public static void ChangeName(ref Person person) { 
     var p = new Person() { Name = "Smith" }; 
     person = p; 
    } 
} 

Try Me

+0

謝謝。但'HandleHttpRequest'的簽名是 'public void HandleHttpRequest(HttpContext context)'。 所以它的論點不是一個參考。 – Tim

+0

其實它是一個參考。引用被傳入。但引用本身並不是通過引用傳遞的。這就是我編寫示例應用程序的原因,因爲它很容易馬上理解。仔細研究我的應用。如果你還有問題,問我。 – CodingYoshi

相關問題