What benefit does the ImmutableObject attribute provide?

僤鯓⒐⒋嵵緔 提交于 2020-01-10 05:09:08

问题


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...

  • ImmutableObjectAttribute Class

Specifies that an object has no subproperties capable of being edited.

So I have this class:

<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)

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:

  • Is the ImmutableObject attribute just a decorative attribute?.

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).


回答1:


From the ImmutableObjectAttribute Class documentation:

This attribute is typically used in the Properties window to determine whether to render an expandable object as read-only. As such, this property is used only at design time.

... so yes, this is only for decoration.



来源:https://stackoverflow.com/questions/34640695/what-benefit-does-the-immutableobject-attribute-provide

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!