简体   繁体   中英

Why can C# static classes contain non-static classes/structs?

I've recently started learning C# and I'm confused about something. The documentation for static classes tells me that they can only contain static members. Yet I can define non-static nested classes and structs within my static class.

I'm guessing that class/struct definitions don't count as members , but why is this allowed? If a nested class of a static class can be instantiated, doesn't that contradict the point of a static class? Am I misunderstanding something obvious here?

In C# nested classes are not subclasses, the surrounding class is more like another namespace. You dont have access to an instance of the outer class from within the inner class(as opposed to fe Java). That's why static classes can contain nested types.

A famous example, the LINQ class Enumerable which is static. It contains many helper classes:

public static class Enumerable
{
    // many static LINQ extension methods...

    class WhereEnumerableIterator<TSource> : Iterator<TSource>
    {
       // ...
    }

    internal class EmptyEnumerable<TElement>
    {
        public static readonly TElement[] Instance = new TElement[0];
    }

    public class Lookup<TKey, TElement> : IEnumerable<IGrouping<TKey, TElement>>, ILookup<TKey, TElement>
    {
        // ...
    }

     // many others
}

So the surrounding static class is a logical container for the inner class. It belongs there because it is used from the static class and often not accessible from somewhere else(if not public).

But you're right, it's a lack of documentation. They should have said:

Contains only static members or nested types

The documentation is a little lacking, but nested classes/structs are allowed in static classes, and can also be static, or can be instantiated. Consider the following code:

namespace StaticClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            new Foo(); // Cannot create an instance of the static class 'Foo'
            new Foo.Bar(); // Cannot create an instance of the static class 'Foo.Bar'
            new Foo.Baz();
        }
    }

    static class Foo
    {
        public static class Bar
        {

        }

        public class Baz
        {

        }
    }
}

In this context, static classes are similar to namespaces, but namespaces (probably) describe the semantic relationships better than nested classes.

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