C# 常用数据参数

发布于 2024-08-17 06:03:20 字数 267 浏览 3 评论 0原文

您好,

我是面向对象和编程的初学者,我遇到以下情况:

我有一组常量值和枚举,我实现的几个类共享它们。

这些类是独立的,即除了共享这些值之外,它们彼此不交互,因此继承它们不起作用。

我想知道;如果我创建一个仅包含这些常量和枚举的空类,然后在每个类中声明这些类的对象,那么我可以使用这些值,例如:

globals.enum.enummember?

这是合理的编程还是有更好的方法来做到这一点?

感谢您抽出时间。

Greetings,

I'm a beginner to OO and programming and I have the following situation:

I have a set of const values and enums that several of the classes I implement share.

These classes are independent i.e. other than sharing these values, they do not interact with each other, so inheriting them won't work.

I was wondering; If I create an empty class with just these consts and enums and then declare an object of these class in each class then i could use these values like:

globals.enum.enummember?

Is this sound programming or is there a better way of doing this?

Thanks for your time.

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

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

发布评论

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

评论(2

与他有关 2024-08-24 06:03:20

最佳实践是简单地与类一起声明枚举,而不是嵌套在类中。实际上,嵌套类型通常不是一个好主意,除非它们是私有的。当然也有例外,但在大多数情况下,不嵌套会更好。

常量必须在类中定义,但不需要实例化该类的对象来使用它们。它们也可以是公共的,因此您不需要继承任何东西。如果您认真思考一下,您应该能够为包含这些常量的类找出一个好名称。

实践表明,常量和枚举很少是全局的。大多数时候,它们与一个或几个类紧密结合。然后,您应该将这些常量定义为适当类的一部分,并将枚举放在与使用它们的类相同的命名空间中。

The best practice is to simply declare the enums alongside with your classes, not nested in a class. Actually, nested types are usually a bad idea, unless they are private. There are exceptions, of course, but for the most part you're better without nesting.

Constants have to be defined in a class, but you don't need to instantiate an object of the class to use them. Also they can be public, so you don't need to inherit anything. If you think about it hard enough, you should be able to figure out a good name for the class that contains these constants.

Practice shows that constants and enums rarely are simply global. Most of the time they are closely coupled with one or few classes. You should then define these constants as a part of the appropriate class and put enums in the same namespace as the class using them.

季末如歌 2024-08-24 06:03:20

您可以使用带有静态成员的静态类来实现所需的行为:

namespace A {
    public static class Enum1 {
       public static readonly int EnumMember1 = 1;
       public static readonly int EnumMember2 = 2;
       public static readonly int EnumMember3 = 3;
    }
}

您应该按以下方式使用它:

int x = A.Enum1.EnumMember2;

You can use static class with static members to achieve desired behavior:

namespace A {
    public static class Enum1 {
       public static readonly int EnumMember1 = 1;
       public static readonly int EnumMember2 = 2;
       public static readonly int EnumMember3 = 3;
    }
}

You should use this in the following way:

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