Class declared inside of another class in C#

前端 未结 7 1134
庸人自扰
庸人自扰 2021-02-02 06:12

I am working on some legacy code and have come across something that I\'m not sure of. We have a class y that is declared inside of another class x.

7条回答
  •  礼貌的吻别
    2021-02-02 06:40

    This has permissions implications. A top-level "class y" would be "internal" - however, here "y" is private to "x". This approach is helpful for implementation details (for example cache rows etc). Likewise, y has access to all private state of x.

    There are also implications with generics; x.y is generic "of T", inherited from the outer class. You can see this here, where Bar has full use of T - and note that any static fields of Bar are scoped per-T.

    class Foo {
        void Test(T value) {
            Bar bar = new Bar();
            bar.Value = value;
        }
        class Bar {
            public T Value { get; set; }
        }
    }
    

    Often people incorrectly think they need to define Bar as Bar - this is now (effectively) doubly generic - i.e. Foo - where TOld is the (now unavailable) T from Foo. So don't do that! Or if you want it to be doubly-generic, pick different names. Fortunately, the compiler warns you about this...

提交回复
热议问题