我想知道,因为可以使用反射完成很多事情,我可以在构造函数完成执行后更改私有只读字段吗?
(注意:只是好奇心)
public class Foo
{
private readonly int bar;
public Foo(int num)
{
bar = num;
}
public int GetBar()
{
return bar;
}
}
Foo foo = new Foo(123);
Console.WriteLine(foo.GetBar()); // display 123
// reflection code here...
Console.WriteLine(foo.GetBar()); // display 456
Run Code Online (Sandbox Code Playgroud) 这是声明不可变结构的正确方法吗?
public struct Pair
{
public readonly int x;
public readonly int y;
// Constructor and stuff
}
Run Code Online (Sandbox Code Playgroud)
我想不出为什么这会遇到问题,但我只想问一下.
在这个例子中,我使用了int.如果我使用了一个类,但该类也是不可变的,就像这样呢?这应该也可以正常工作,对吧?
public struct Pair
{
public readonly (immutableClass) x;
public readonly (immutableClass) y;
// Constructor and stuff
}
Run Code Online (Sandbox Code Playgroud)
(旁白:据我所知,使用性能更加普及,并允许改变,但这种结构的目的是从字面上只存储两个值我在永恒的问题只是有兴趣在这里.)
我发现人们声称使用类中的所有只读字段并不一定使该类的实例不可变,因为即使在初始化(构造)之后,仍有"方法"来更改只读字段值.
怎么样?有什么方法?
所以我的问题是我们什么时候才能在C#中真正拥有一个"真正的"不可变对象,我可以安全地在线程中使用它?
匿名类型也创建不可变对象吗?有人说LINQ在内部使用了不可变的对象.究竟怎么样?