为什么只读结构中的属性不能写,而类却可以? [英] Why property in read only structure can't be write while class can ?
本文介绍了为什么只读结构中的属性不能写,而类却可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我很好奇为什么不能在设置只读类的同时设置只读结构的属性?
I'm curious why can't property in read only struc be set while read only class can be set ?
public struct A {
int C;
public int X { get { return C; } set { C = value; } }
}
public class B
{
int C;
public int X { get { return C; } set { C = value; } }
}
public static class C{
public static readonly A Ax = new A();
public static readonly B Bx = new B();
public static void Main() {
Ax.X = 10; //Got error here.
Bx.X = 10;
}
}
推荐答案
即使更改值类型的状态,也会更改对象标识.
Even when you change the state of a value type, you change the object identity.
请确保您要使用值类型-它们以非常不直观的方式工作.
Be very sure you want a value type - they work in a very non-intuitive way.
这篇关于为什么只读结构中的属性不能写,而类却可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文