为什么我们可以从作为值传递给方法的参数获取更新结果?

时间:2017-02-16 18:48:30

标签: c#

在程序中,调用名为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)

所以它的论点不是参考。

1 个答案:

答案 0 :(得分: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