[英]How to check whether there is within the class of the same class?
I'am sorry for my Engilsh. 我很抱歉我的Engilsh。 I have some class like this: 我有这样的课:
public class MainClass
{
public string message { get; set; }
public MainClass forward { get; set; }
}
And have Main funcion, where I'am inizialize class and fill data(in real project I have data in JSON format, where class can be embedded itself in an infinite number of times) of class: 并且有主要功能,我在这里使用类和填充数据(在实际项目中我有JSON格式的数据,其中类可以无限次地嵌入其中):
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 do I get the number of nested class names , without knowing their number? 如何在不知道其编号的情况下获取嵌套类名的数量?
It sounds like you just want recursion: 听起来你只想要递归:
public int GetNestingLevel(MainClass mc)
{
return mc.forward == null ? 0 : GetNestingLevel(mc.forward) + 1;
}
Or as part of MainClass
itself: 或者作为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: 或者在C#6中,如果要使用null条件运算符:
public int GetNestingLevel()
{
return (mc.forward?.GetNestingLevel() + 1) ?? 0;
}
That could cause problems if you have very deeply nested classes, in terms of blowing the stack - but it's probably the simplest approach otherwise. 如果你有非常深层次的嵌套类,就吹掉堆栈而言,这可能会导致问题 - 但它可能是最简单的方法。 The alternative is to use iteration, as per M.kazem Akhgary's answer. 根据M.kazem Akhgary的回答,另一种方法是使用迭代。
You can go forward and count! 你可以前进并数数!
int count = 0;
MainClass tempClass = clasClass;
while (tempClass.forward != null)
{
count++;
tempClass = tempClass.forward;
}
Also you can make this a bit smaller. 你也可以把它做得更小一些。
int count = 0;
MainClass tempClass = clasClass;
while ((tempClass = tempClass.forward) != null) count++;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.