简体   繁体   中英

How can I create a property in C# for a nested private enum

How can I create a public property in a class for a nested private enum? I want to be able to use that enum also outside of this class but not in all places outside thats why I'm doing so.

I would also want to know if it is right to act like that or shall I use another convention, like writing the enum under the same namespace but than I will enable an global use of this enum by all the classes in the namespace which is not good.

Just to make it more clear: the enum holds different types of fuel That's why I don't want electric car to know this enum and also other classes which can use it accidentally and are placed under the same namespace.

You can't do this. The compiler will complain about inconsistent accessibility. How can a method return something no one knows about? Make the enum public or internal , otherwise no one can use it.

Specify the enum as internal so it will be visible to all classes within an assembly but not usable to objects in other assemblies. Like this:

internal enum MyVals
{
    val1,
    val2,
}

The obvious caveat is that you would have to make sure that you split your biz logic into separate assemblies, not just namespaces.

Sounds to me like your design is wrong. I'm not sure of your classes, but maybe the design below may help you. It's also easy to read and makes sense.

public class BaseCar
{
  //Basic functions for other cars to use
  void Drive();
  void Stop();
}

public class GasCar : BaseCar
{
  // Enum is specific to a car with gas
  public Enum FuelType ....
}

public class ElectricCar : BaseCar
{
  //No gas FueType Enum for electric car...
}

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