How to check if a class has the same class?

I regret my Engilsh. I have a class like this:

public class MainClass
{
      public string message { get; set; }
      public MainClass forward { get; set; }
}

And I have Main funcion, where I initialize the class and fill in the data (in a real project, I have data in JSON format, where the class can be built in an infinite number of times) of the class:

static void Main(string[] args)
{
    MainClass clasClass = new MainClass()
    {
        message = "Test1",
        forward = new MainClass()
        {
            message = "Test1_1",
            forward = new MainClass() 
            {
                message = "Test1_1_1",
                forward = new MainClass()
                {
                    message = "Test1_1_1_1",
                    forward = new MainClass()
                }   
            }
        }
    };
}

How to get the number of nested class names without knowing their number?

+4
source share
2 answers

You can go ahead and reckon!

int count = 0;
MainClass tempClass = clasClass;
while (tempClass.forward != null)
{
    count++;
    tempClass = tempClass.forward;
}

You can also do it a little less.

int count = 0;
MainClass tempClass = clasClass;
while ((tempClass = tempClass.forward) != null) count++;
+2
source

Looks like you just want recursion:

public int GetNestingLevel(MainClass mc)
{
    return mc.forward == null ? 0 : GetNestingLevel(mc.forward) + 1;
}

Or as part of MainClass:

public int GetNestingLevel()
{
    return mc.forward == null ? 0 : mc.forward.GetNestingLevel() + 1;
}

Or in C # 6, if you want to use the null conditional operator:

public int GetNestingLevel()
{
    return (mc.forward?.GetNestingLevel() + 1) ?? 0;
}

, , , - , , . , . .

+4

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


All Articles