首页 > 解决方案 > 在 dll 项目中使用递归函数

问题描述

好的,所以我创建了一个 dll 项目。此 dll 项目使用树类结构来保存数据,并具有用于处理该数据的函数。

所以在 dll 项目中我们有:

namespace Engine
{
   public class Engineclass
   {
       public Component SolutionTree = new Component();

       public Component ReturnComponent(string ComponentName)
       {
           Component CurrentComp = SolutionTree;
           if(CurrentComp.Name != ComponentName)
           {
               CurrentComp = RecurseForName(CurrentComp, ComponentName);
           }

           return CurrentComp;
        }

        public Component RecurseForName(Component CompORG, ComponentName)
        {
            Component FoundComp = null;

            if (!string.IsNullOrEmpty(ComponentName) && (CompORG != null))
            {
                if (CompORG.ComponentName.ToUpper().Trim() ==
                    ComponentName.ToUpper().Trim())
                {
                    return CompORG;
                }

            foreach (var CompNew in CompORG.ActiveComponents)
            {
                var FoundComp2 = RecurseForName(CompNew, ComponentName);
                if (FoundComp2 != null)
                {
                    return FoundComp2;
                }
            }
        }

        return FoundComp;
        }
    }
}

组件类是:

public class Component
{
    public string Name {get; set;}
    public List<Component> ActiveComponents { get; set; }

    public Component()
    {
        this.ActiveComponents = new List<ActiveComponent>();
    }
}

现在在我的控制台应用程序中我正在对其进行测试,我加载 dll 并填充解决方案树。IE

EngineClass EC = new EngineClass();

EC.Component NewComp = new EC.Component();

EC.Name = "bob";

EC.Component NewSubComp = new EC.Component();

EC.Name = "Son of Bob";

NewComp.ActiveComponents.add(NewSubComp);

EC.SolutionTree = NewComp;

一切正常。

但是,当我尝试使用递归函数返回特定组件时,我得到一个 System.NullReferenceException:'对象引用未设置为对象的实例。

var FoundASon = EC.FindComponent("Son of Bob");

它发生在函数的return CompORG;行上。RecurseForName

所以,我知道CompOrg不是null,而且里面的名字CompOrg已经匹配,但是试图返回CompOrg会导致nullreferenceexception!

我真的需要帮助解决这个问题,因为调试已编译的 dll 非常困难。

ps dll 项目有单元测试,它们通过功能正常工作。

标签: c#.net

解决方案


推荐阅读