如何在 C# 中为嵌套私有枚举创建属性

发布于 2024-10-31 03:52:45 字数 223 浏览 0 评论 0原文

如何在类中为嵌套私有枚举创建公共属性? 我希望能够在这个类之外使用该枚举,但不能在类之外的所有地方使用,这就是我这样做的原因。

我还想知道这样做是否正确,或者我应该使用另一种约定,例如在同一名称空间下编写枚举,但我将允许名称空间中的所有类全局使用该枚举,而这不是好的。

只是为了更清楚:枚举包含不同类型的燃料 这就是为什么我不希望电动汽车知道这个枚举以及其他可能意外使用它并放置在同一命名空间下的类。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

濫情▎り 2024-11-07 03:52:45

你不能这样做。编译器会抱怨可访问性不一致。一个方法怎么能返回一些没人知道的东西呢?将enum设置为publicinternal,否则没有人可以使用它。

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.

满意归宿 2024-11-07 03:52:45

在我看来,你的设计是错误的。我不确定你的课程,但也许下面的设计可以帮助你。它也很容易阅读并且有意义。

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...
}

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...
}
疯到世界奔溃 2024-11-07 03:52:45

将枚举指定为 internal对程序集中的所有类都可见,但对其他程序集中的对象不可用。像这样:

internal enum MyVals
{
    val1,
    val2,
}

明显的警告是,您必须确保将业务逻辑拆分为单独的程序集,而不仅仅是命名空间。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文