简体   繁体   English

在C#中声明私有静态类有什么用?

[英]Any use of declaring a private static class in c#?

Is there any use of declaring a static class as private.Here is the code below: 将静态类声明为私有有什么用,下面是代码:

static class DerivedClass
{
    private static string GetVal()
    {
        return "Hello";
    }
}

The sample code you provided actually illustrates an internal class, not a private class. 您提供的示例代码实际上说明了一个内部类,而不是私有类。 This is perfectly fine and is done all the time. 这是完全可以的,并且始终可以完成。 It means the methods of the class are available from other classes within the same module, but not externally. 这意味着该类的方法可从同一模块中的其他类获得,但不能从外部获得。

If you mean declaring private members of static classes, sure there is. 如果您要声明静态类的私有成员,请确保存在。

static class DerivedClass
{
    public static string GetVal()
    {
        return GetValInternal();
    }

    private static string GetValInternal()
    {
        return "Hello";
    }
}

If you mean declaring a private static nested classes (because only nested classes can be private, according to the documentation ), then you can do it, but there's probably no reason to do it. 如果您要声明一个私有静态嵌套类(根据文档 ,因为只有嵌套类可以是私有的),则可以这样做,但是可能没有理由这样做。

class SomeClass
{
    private static class DerivedClass
    {
        public static string GetVal()
        {
            return "Hello";
        }
    }
}

Is equivalent to 相当于

class SomeClass
{
    private static string GetVal()
    {
        return "Hello";
    }
}

By default classes with no access modifiers like in your example are internal , not private . 默认情况下,像您的示例一样,没有访问修饰符的类是内部的 ,而不是私有的 See this reference: http://msdn.microsoft.com/en-us/library/ms173121.aspx . 请参阅此参考: http : //msdn.microsoft.com/zh-cn/library/ms173121.aspx This means that you can access this class from anywhere inside the library/project. 这意味着您可以从库/项目内部的任何位置访问此类。 This makes sense because it allows you to use the class internally without necessarily exposing it to the outside world. 这是有道理的,因为它允许您在内部使用该类,而不必将其暴露给外界。

Explicitly declaring it as private however makes sense in some rare cases only in my opinion. 但是,仅在我看来,在一些极少数情况下,明确将其声明为私有是有意义的。 I have used it before for nested classes simply to group certain things together and make my code prettier/more readable. 我以前在嵌套类中使用过它,只是将某些东西组合在一起并使我的代码更漂亮/更易读。 However I find that if I am creating nested classes it usually means that I need to redesign my code and pull some of it into separate files and separate classes. 但是我发现,如果要创建嵌套类,通常意味着我需要重新设计代码,并将其中的一些代码拉到单独的文件和单独的类中。 Rather try to stick to one class per file. 而是尝试坚持每个文件一个类。

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

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