Nested types or another solution for one mapped class

I have a class for which some functions need to be encapsulated in some way.

I was thinking of a nested class and adding this functionality to it plus some states. The relationship between these two classes is one-to-one.

The problem is that to access external class variables or methods, they must be declared static, and I do not want this. Another solution passes the reference of the outer class to the inner class.

What is the best practice for my problem?

+3
source share
3 answers
using System;

class OuterType
{
    private static OuterType _instance;

    public OuterType()
    {
        _instance = this;
    }

    private String Message
    {
        get { return "Hello from OuterType"; }
    }

    public void testInnerType()
    {
        InnerType innerType = new InnerType();
        Console.WriteLine(innerType.FormattedOutertMessage);
    }

    private class InnerType
    {
        private readonly OuterType _outerType = _instance;

        public String FormattedOutertMessage
        {
            get { return _outerType.Message.ToUpper(); }
        }
        // InnerType doesn't need to dispose any object of OuterType.
    }
}

Then it works as follows:

class Program
{
    static void Main(string[] args)
    {
        OuterType outerType = new OuterType();
        outerType.testInnerType();
        Console.ReadKey();
    }
}

But I'm not sure if this is a good idea or not ?!

0
source

, , , , "", , , - .

, , , :

  • ? - , : OuterType + InnerType

  • , ( ).

  • Visual Studio ( ), , FxCop, .

, .

+1

6 , . 20 "" , , , .

, , 1 1 .

( ) 'this' , .Parent . - GC, .

( ) , , . , GC , , . , , , .

, :

Parent
 |
 +-Child1
 |
 +-Child2

Child, , .

ADO.Net , , .

+1

Source: https://habr.com/ru/post/1783789/


All Articles