简体   繁体   中英

Can I access enums without having to type out the enum type?

Enum EventType = {Click, Jump, Etc};

Instead of accessing it like like this:

EventType.Jump

is there any way to do so without the "EventType." prefix?

Jump

No, but if you really want, you can use local references in you class for that:

class A
{
   private EventType Jump = EventType.Jump;


   if(actionEvent.Type == Jump)......
}

Actually not. In C++ this was actually a long standing pain in the neck as scoped enums were not possible up to C++11 (without workarounds)

For C# you cannot do this as this would potentially introduce name collisions eg:

Enum EventType1 = {Click, Jump, Etc};
Enum EventType2 = {Click, Jump, Etc};

Which Jump should be used now?

Short Answer: No. You can't use an enum member with using EnumType.

Instead of Enum you can define a const int Jump = 1 and then code accordingly, but

Why do you want something like this ?

Consider using enums instead of const, It will improve readability.

As stated by the other answers, you can't omit the enum prefix in C#, however, if the goal is prevent having to type long enum names (although intellisense solves that quite a bit), or keep shorter code, you can use an alternative by putting an alias inside the using clause on top. (although this will only be valid inside that specific class) eg

using s = SomeLongEnumerationNameYouDontWantToSee;
...
if(foo == s.Bar) ..

or a real world enum:

using ds = System.Drawing.Drawing2D.DashStyle;
...
ds.Solid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM