C#:为什么 Networkstream.Read() 能够在没有 out/ref 关键字的情况下更改缓冲区变量
C#: Why is Networkstream.Read() able to change the buffer variable without out/ref keyword
为什么NetworkStream.Read()可以写入byte[]?
byte[] data = new byte[16];
NetworkStream ns = new NetworkStream(socket);
ns.Read(data, 0, data.Length);
//data != new byte[16]
我认为您需要 out/ref 关键字来写入变量。像这样:
ns.Read(out data, 0, data.Length);
如果我尝试重新创建该方法,它不起作用:
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]
但是如果我将 "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]
这证明您不能在没有 "out"/"ref" 关键字的情况下写入变量。但是没有"out"/"ref"关键字,NetworkStream如何写入byte[]呢?
可怕..
很可能是因为它不执行 buffer = data
分配。相反,它直接读入作为参数传递的缓冲区,即如果你在循环中执行 buffer[i] = 1
,你将模拟它。
This proofs that you cant write to a variable without the "out"/"ref" keyword.
您需要在心理上区分两个截然不同的概念:
- 改变对象的状态
- 重新分配变量(参数、本地、字段等)的值
(注意在对象的情况下,后者意味着改变它所指的对象)
out
只需要 second。 Stream
允许调用者传入一个对象(数组),并将其写入数组。这不需要 out
。与以下内容没有什么不同:
void SetCustomerName(Customer obj) { // for class Customer
obj.Name = "Fred";
}
...
var x = new Customer();
SetCustomerName(x);
Console.WriteLine(x.Name); // prints "Fred"
这会更新对象,但不需要更改参数。它更改参数指向的对象。
为什么NetworkStream.Read()可以写入byte[]?
byte[] data = new byte[16];
NetworkStream ns = new NetworkStream(socket);
ns.Read(data, 0, data.Length);
//data != new byte[16]
我认为您需要 out/ref 关键字来写入变量。像这样:
ns.Read(out data, 0, data.Length);
如果我尝试重新创建该方法,它不起作用:
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]
但是如果我将 "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]
这证明您不能在没有 "out"/"ref" 关键字的情况下写入变量。但是没有"out"/"ref"关键字,NetworkStream如何写入byte[]呢? 可怕..
很可能是因为它不执行 buffer = data
分配。相反,它直接读入作为参数传递的缓冲区,即如果你在循环中执行 buffer[i] = 1
,你将模拟它。
This proofs that you cant write to a variable without the "out"/"ref" keyword.
您需要在心理上区分两个截然不同的概念:
- 改变对象的状态
- 重新分配变量(参数、本地、字段等)的值
(注意在对象的情况下,后者意味着改变它所指的对象)
out
只需要 second。 Stream
允许调用者传入一个对象(数组),并将其写入数组。这不需要 out
。与以下内容没有什么不同:
void SetCustomerName(Customer obj) { // for class Customer
obj.Name = "Fred";
}
...
var x = new Customer();
SetCustomerName(x);
Console.WriteLine(x.Name); // prints "Fred"
这会更新对象,但不需要更改参数。它更改参数指向的对象。