Avoiding disposing system-defined Pen and Brush in

2019-03-25 07:38发布

I understand it is best practise to call Dispose() on instances of Pen and Brush, except if they've been set to the system-predefined values (eg. System.Drawing.Brushes, System.Drawing.Pens or System.Drawing.SystemBrushes)

Trying to dispose a system-defined resource results in an exception being thrown.

It doesn't appear to be obvious how you can detect (apart from wrapping the Dispose() call in a try/catch) whether one of these resources is referencing a system-defined or user-defined value.

8条回答
forever°为你锁心
2楼-- · 2019-03-25 08:04

Only thing come in mind is to have a practice do not use System pens/brushes as parameters to methods.

查看更多
萌系小妹纸
3楼-- · 2019-03-25 08:14

Just for completeness, using Reflector I see that the System.Drawing.Pen and System.Drawing.SolidBrush classes have a private field named 'immutable'.

This field appears to be set to true when the object refers to a system-defined resource, so you could use reflection to carefully check the value of this field to decide whether to call Dispose() on it.

查看更多
登录 后发表回答