How is ImmutableObjectAttribute used?

非 Y 不嫁゛ 提交于 2019-12-08 15:07:09

问题


I was looking for a built-in attribute to specify that a type is immutable, and I found only System.ComponentModel.ImmutableObjectAttribute.

Using Reflector, I checked where it was used, and it seems that the only public class that uses it is System.Drawing.Image... WTF? It could have been used on string, int or any of the primitive types, but Image is definitely not immutable, there are plenty of ways to alter its internal state (using a Graphics or the Bitmap.SetPixel method for instance).

So the only class in the BCL that is explicitly declared as immutable, is mutable! Or am I missing something?


回答1:


The documentation states:

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.

Reflector shows that the only method using this attribute is the internal System.Windows.Forms.PropertyGridInternal.GridEntry.Flags property getter used by design property grids.




回答2:


I think you have the usage of ImmutableObjectAttribute confused -- it means that the object's properties should not be editable in a form designer or similar design-time UI, not that the object is itself immutable.

This attribute is probably a candidate for the Daily WTF, however...




回答3:


Look at the documentation for ImmutableObjectAttribute: "Specifies that an object has no subproperties capable of being edited... 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 this attribute isn't really about immutability: it's about disabling the display/editability of subproperties in an editor like a PropertyGrid.

So Image isn't being declared as immutable, not Int32 as mutable. Int32 doesn't need ImmutableObjectAttribute because it isn't expandable anyway. Image has it because it would be expandable, but not usefully so. It's just a really, really misleading name.



来源:https://stackoverflow.com/questions/1691246/how-is-immutableobjectattribute-used

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