ImmutableObject属性有什么好处? [英] What benefit does the ImmutableObject attribute provide?
问题描述
我只是出于好奇心而测试ImmutableObjectAttribute
属性,看看是否可以通过应用它获得一些好处,或者仅仅是出于语义修饰...
I was testing the ImmutableObjectAttribute
attribute just for curiosity to see if I could gain some beneffits applying it, or if it was just for semantic decoration...
指定对象没有能够编辑的子属性.
Specifies that an object has no subproperties capable of being edited.
所以我有这节课:
<ImmutableObject(True)>
Public Class TestClass
<ImmutableObject(True)>
Public sb As StringBuilder
Public Sub New()
sb = New StringBuilder
End Sub
End Class
我已经用以下代码进行了测试:
And I've tested with this code:
Dim obj As New TestClass
obj.sb.Append("Hello")
obj.sb.Append(" ")
obj.sb.Append("World")
MsgBox(obj.sb.ToString)
然后,在可变对象中应用了ImmutableObject
属性后,我希望看到某种编译器警告,某种运行时异常,或者只是从
Then, after I'd applied the ImmutableObject
attribute in a mutable object, I expected to see some kind of compiler warning, some sort of runtime exception, or just receive an unexpected value from the internal string of the StringBuilder
, but nothing of that things happened, all seems to work as normally.
这使我想到了一个答案似乎很明显的问题,但我需要问一下:
That makes me think a question whose answer seems obvious, but I need to ask it:
-
ImmutableObject
属性仅仅是装饰性属性吗?
- Is the
ImmutableObject
attribute just a decorative attribute?.
那么为什么存在这个属性?我找不到用该属性标记类的任何好处,它不能确保成员真正是不可变的,或者至少不能确保.Net理解为不可变的(您知道,就像String在.Net中并不是真正不变的那样).
Why exists this attribute then? I cannot find any beneffit marking a class with this attribute it it not ensures that the members are really immutable, or at least what .Net understands for immutable (you know, like a String is not really immutable in .Net).