简体   繁体   English

C#:为什么Networkstream.Read()能够在没有out / ref关键字的情况下更改缓冲区变量

[英]C#: Why is Networkstream.Read() able to change the buffer variable without out/ref keyword

Why can NetworkStream.Read() write to the byte[]? 为什么NetworkStream.Read()可以写入byte []?

byte[] data = new byte[16];

NetworkStream ns = new NetworkStream(socket);
ns.Read(data, 0, data.Length);

//data != new byte[16]

I thought you need a out/ref keyword to write to a variable. 我以为您需要out / ref关键字才能写入变量。 like this: 像这样:

ns.Read(out data, 0, data.Length);

If i try to recreate that method it doesnt work: 如果我尝试重新创建该方法,它将不起作用:

public static void testread(byte[] buffer, int size)
{
    byte[] data = new byte[size];
    for (int i = 0; i < data.Length; i++)
    {
        data[i] = 1;
    }
    buffer = data;
}

byte[] data = new byte[16];
testread(data, data.Length);

//data == new byte[16]

But if I add the "out" keyword to testread() does work: 但是,如果我将“ out”关键字添加到testread()确实可以工作:

public static void testread(out byte[] buffer, int size)
{
    byte[] data = new byte[size];
    for (int i = 0; i < data.Length; i++)
    {
        data[i] = 1;
    }
    buffer = data;
}

byte[] data = new byte[16];
testread(data, data.Length);

//data != new byte[16]

This proofs that you cant write to a variable without the "out"/"ref" keyword. 这证明没有“ out” /“ ref”关键字就无法写入变量。 But how does NetworkStream write to the byte[] without the "out"/"ref" keyword? 但是NetworkStream如何在没有“ out” /“ ref”关键字的情况下写入byte []? Scary.. 害怕..

This proofs that you cant write to a variable without the "out"/"ref" keyword. 这证明没有“ out” /“ ref”关键字就无法写入变量。

You need to mentally separate two very different concepts: 您需要在思想上将两个截然不同的概念分开:

  • changing the state of an object 改变物体的状态
  • reassigning the value of a variable (parameter, local, field, etc) 重新分配变量的值(参数,局部,字段等)

(noting that in the case of objects, the latter means changing the object that it refers to) (注意,对于对象,后者意味着更改它所引用的对象)

out is only needed for the second of these. out时,才需要对这些第二 Stream allows the caller to pass in an object (the array), and it writes into the array. Stream允许调用者传入一个对象(数组),并将其写入数组。 No out is needed for this. 没有out需要这一点。 It is no different to: 与以下内容没有什么不同:

void SetCustomerName(Customer obj) { // for class Customer
    obj.Name = "Fred";
}
...
var x = new Customer();
SetCustomerName(x);
Console.WriteLine(x.Name); // prints "Fred"

This updates the object, but doesn't need to change the parameter to do so. 这将更新对象,但不需要更改参数即可。 It changes the object that the parameter points to . 它更改参数指向对象

Most likely because it doesn't do the buffer = data assignment. 最有可能是因为它不执行buffer = data分配。 Instead it reads directly into the buffer passed as the argument, ie if you do buffer[i] = 1 in your loop you emulate it. 相反,它直接读入作为参数传递的缓冲区,即,如果在循环中执行buffer[i] = 1 ,则可以对其进行仿真。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM