简体   繁体   English

为什么我们在C#中将内部类用于常量?

[英]Why do we use internal classes for constants in C#?

I have seen it in many projects. 我在很多项目中都看到了。 Why do developers use internal classes to store the constant variables in C#? 开发人员为什么要使用内部类在C#中存储常量变量?

For instance: 例如:

internal static class Constants
{
    public const double Pi = 3.14159;
    public const int SpeedOfLight = 300000; // km per sec.
}

Simply, the designer decided that this class need to be used within the same assembly. 简单地说,设计人员认为此类需要在同一装配中使用。 And it is not to be exposed to or accessed from any project referencing the assembly. 并且不应将其公开或从引用该程序集的任何项目中访问。

When you download a Nuget package, you can't access classes that are internal. 当您下载Nuget程序包时,您将无法访问内部的类。 The developers decided that you don't need to access these. 开发人员认为您不需要访问它们。 So these values are "private" for this package. 因此,这些值对于此软件包是“私有”的。

More on access modifiers: 有关访问修饰符的更多信息:

public :Access is not restricted. public:访问不受限制。

protected :Access is limited to the containing class or types derived from the containing class. protected:访问仅限于包含的类或从包含的类派生的类型。

internal: Access is limited to the current assembly. 内部:访问仅限于当前程序集。

protected internal : Access is limited to the current assembly or types derived from the containing class. protected internal:访问仅限于当前程序集或从包含类派生的类型。

private : Access is limited to the containing type. private:访问仅限于包含类型。

While most answers describe the meaning of internal they are missing a part of the question I think: Why put constants in a inner class? 尽管大多数答案都描述了internal的含义,但它们却缺少了我认为的一部分问题: 为什么将常量放入内部类中?

This is mostly because it can they desire to identify constants through something feeling like a namespace: 这主要是因为他们可以希望通过某种感觉像是名称空间来标识常量:

double myValue = Constants.Pi * 10;

Or 要么

double myValue = OtherClass.Constants.Pi * 10;

Without the inner class they would look more like members/properties. 没有内部类,它们将更像成员/属性。 At least when they do not use UPPER_CASING for the naming. 至少当他们不使用UPPER_CASING命名时。

To make the answer complete: The internal is used to protect the constant against using them outside of the assembly. 要使答案完整: internal用于保护常量,以防止在组件外部使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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