简体   繁体   中英

Setting an enum as another enum within a C# class

I'm currently working on a C# program that utilizes a fair number of enums. It's organized in such a way that a class contains many enums, and there are several of these classes. However, a couple enums are identical between the two--for organizational purposes, it would be nice to have a kind of 'SharedEnums' class, and then do something like this:

public class FirstEnumCollection {
    public enum Fruits = SharedEnums.Fruits;
    //insert non-shared enums here
}

public class FirstEnumCollection {
    public enum Fruits = SharedEnums.Fruits;
    //insert non-shared enums here
}

public class SharedEnums { 
    public enum Fruits {
        Apple,
        Pear
    }
}

This way, we won't have the same enums declared multiple times across classes, and changing the shared enum will change the enum in both classes. I've tried several variations of my example without luck, and I'm fairly certain it can't be done, but would like confirmation.

An enum doesn't need to "belong" to a class. You can declare it outside of any class:

public enum Fruits {
    Apple,
    Pear
}

and then use it within any class.

An enum can be defined at namespace scope, you are not required to create an enum inside a class. You can imagine an enum like a struct, or a class, it's a type that you can use in the code. So, define it at namespace scope

namespace MyCode
{
    public enum Days { M, T, W, T, F, Sa, Su }
}

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