为什么可以通过ref参数修改只读字段? [英] Why can readonly fields be modified through ref parameters?
问题描述
考虑:
class Foo
{
private readonly string _value;
public Foo()
{
Bar(ref _value);
}
private void Bar(ref string value)
{
value = "hello world";
}
public string Value
{
get { return _value; }
}
}
// ...
var foo = new Foo();
Console.WriteLine(foo.Value); // "hello world"
这甚至如何编译,但仍然有效?我不应该为构造函数之外的 _value
字段分配不同的值,因为它用 readonly
标记.但是,通过ref
传递给一个方法,确实是可以操作的.
How does this even compile, nonetheless work? I should not be able to assign a the different value to _value
field outside of the constructor, as it's marked with readonly
. However, pass it by ref
to a method, and it can indeed be manipulated.
这很危险吗?为什么?我感觉不对,但我无法完全理解它.
Is this dangerous? Why? It feels wrong to me, but I can't quite put my finger on it.
推荐答案
它可以编译,因为您只是在构造函数中将值作为 ref
参数传递(其中 readonly
允许设置字段).如果您将对 Bar()
的调用移动到其他方法中,它将失败.
It compiles because you're only passing the value as a ref
parameter in the constructor (where readonly
fields are allowed to be set). If you moved your call to Bar()
into some other method, it would fail.
class Foo
{
private readonly string _value;
public Foo()
{
Bar(ref _value);
}
public void Baz()
{
Bar(ref _value);
}
private void Bar(ref string value)
{
value = "hello world";
}
public string Value
{
get { return _value; }
}
}
上面的代码提供了一个非常明显的编译器错误:
The above code provides a very telling compiler error:
只读字段不能传递 ref 或 out(构造函数中除外)
A readonly field cannot be passed ref or out (except in a constructor)
这篇关于为什么可以通过ref参数修改只读字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!