.NET Nested Classes

2019-02-28 07:10发布

The current class library I am working on will have a base class (Field) with over 50 specific "field" types which will inherit from "Field" and nested for maintain readability. For example...

abstract class Field
{
    public int Length { get; set; }

    public class FieldA : Field
    {
        public static void DoSomething()
        {
            Console.WriteLine("Did something.");
        }
    }
}

So far everything looks good and I can use the code as shown:

class Program
{
    static void Main(string[] args)
    {
        Field.FieldA.DoSomething();
    }
}

However, why does this work as well? What is going on here that allows the compiler / IDE intellisense to continue to chain these "FieldA"'s?

class Program
{
    static void Main(string[] args)
    {
        Field.FieldA.FieldA.FieldA.FieldA.FieldA.FieldA.FieldA.DoSomething();
    }
}

It's not application breaking by any means, but thought it was peculiar. Does the same thing in Boo (which is the actual language being used for the library).

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-02-28 07:17

Sounds like you wanted something like:

abstract class Field
{
    public int Length { get; set; }
}

public class FieldA : Field
{
    public static void DoSomething()
    {
        Console.WriteLine("Did something.");
    }
}

Otherwise you're defining a base class with an inner class in it, which inheritorrs will also get. So when you inherit from the outer class to make the inner class, you're starting a loop.

查看更多
做个烂人
3楼-- · 2019-02-28 07:26

FieldA inherits a reference to class FieldA which inherits a reference to class FieldA which inherits a reference to class FieldA which inherits a reference to class FieldA which inherits a reference to class FieldA which inherits a reference to class FieldA which inherits a reference to class FieldA which...

It works because that's what you told it to do.

查看更多
SAY GOODBYE
4楼-- · 2019-02-28 07:40
  1. Field has a public nested-class named FieldA
  2. FieldA inherits from Field
  3. thus you can always access FieldA from FieldA.

The reference isn't creating infinite chains, it is simply pointing to the same class. (some test code)

When you access FieldA.FieldA, the latter FieldA is accessible due to the fact that the former FieldA is an instance of Field so the latter FieldA actually access Field.FieldA

查看更多
登录 后发表回答