I think that many C# developers collided with a such problem: there is some enumeration in standart .net library and many standart classes and their methods to work with them. But if you want to extend this enum by adding some fields that is not possible, but It can efficiently simplify process of developing and can't disturb working of those standart classes. I describe It by concrete example: There is an enum TraceOptions in the System.Diagnostics namespace and it is used by TraceListeners. Let's I want to design Listener with some extra options (like AssemblyName and so on). Now I must to create new enum containing all of my extra options which supplement options from TraceOptions enum. Then to add new property ExtraTraceOptions to my Lis开发者_Go百科tener. But what if I can to write something like this:
enum MyExtraEnum : TraceOptions
{
AssemblyName = 128
}
MyExtraEnum will extend TraceOptions by new fields, which must not intersect with fields of TraceOptions nor by names, nor by values. Then I can use TraceOptions with new fields like:
TraceOptions t = TraceOptions.AssemblyName; (IntelliSense may display that this
field is extended field from MyExtraEnum enumeration)
I understand that this can corrupt existing code using TraceOptions enum, but If I am sure that It will not happen and all resposibility for using such features is lying on me.
What do you do about such feauture?
This doesn't sound like a very good idea to me. So now C# 6 is out, and TraceOptions
has a new feature: SomeFoo = 128
. Or maybe a AssemblyName = 127
. And now you have a collision, which (unlike regular subclassing) the provider of TraceOptions
is not expecting.
Enums provide a limited set of options, which the author of the enum supports. Stating that you take full responsibility is not good enough. It's like asking all member variables will be public, stating you'll never misuse them. That's just not a safe programming approach.
You cant inherit from an enum, all enums are implicitly sealed. So there is no easy way to add an extra value to an enum (if this is what you are trying to do). You would have to define a new enum.
If you want to add extra methods to an enum you can use extension methods but that's about the only way you can extend them.
精彩评论