首页 文章

类库命名空间层次结构不起作用

提问于
浏览
1

我试图在我的类库中实现C#中使用的命名空间层次结构 . 这是我想要做的:

namespace Parent
{
    namespace Child
    {
        Class ChildClass {  }
    }

    Class ParentClass {  }
}

编译类库后它没有按预期工作 . 这是我的预期工作原理 .

要访问 ChildClass ,必须 using Parent.Child . 但是只能通过 using Parent 访问 ParentClass .

我可以在不编译类库的情况下执行此操作,但将cs文件添加到项目中 . 但是当我编译为DLL并将其作为项目中的引用添加时,我无法访问子命名空间 .

更新:我为每个类都有不同的文件 . 当我将所有名称空间和类写入一个文件时,它似乎工作 . 但为什么?

无论如何在C#中实现这一点?

2 回答

  • 0

    我觉得你的 class 缺失 public ;以下代码适合我 .

    namespace Parent
    {
        namespace Child
        {
            public class ChildClass { }
        }
        public class ParentClass
        {
        }
    }
    

    我可以创造;

    Parent.ParentClass p;
    Parent.Child.ChildClass c;
    

    这是您的预期工作原理 .

    编辑:为每个类方法单独的cs文件;

    ParentClass.cs

    namespace Parent
    {
        public class ParentClass{ }
    }
    

    ChildClass.cs

    namespace Parent
    {
        namespace Child
        {
            public class ChildClass { }
        }
    }
    

    这似乎对我有用 .

  • 0

    你正在嵌套类和名称空间,这一切似乎有点困惑 . 为什么不保持更平坦的命名空间结构并在类中进行嵌套 . 请记住,您不需要嵌套名称空间或类来维护父子关系 .

    阅读以下内容:Parent child class relationship design pattern

    这应该让你开始朝着正确的方向前进:

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace ConsoleApplication2
    {
        using System;
        using System.Collections.Generic;
    
        public class ChildClass
        {
            private ParentClass parent;
    
            public ChildClass(ParentClass parentIn)
            {
                parent = parentIn;
            }
    
            public ParentClass Parent
            {
                get { return parent; }
            }
        }
    
        public class ParentClass
        {
            private List<ChildClass> children;
    
            public ParentClass()
            {
                children = new List<ChildClass>();
            }
    
            public ChildClass AddChild()
            {
                var newChild = new ChildClass(this);
                children.Add(newChild);
                return newChild;
            }
        }
    
    
        public class Program
        {
            public static void Main()
            {
                Console.WriteLine("Hello World");
    
                var p = new ParentClass();
                var firstChild = p.AddChild();
                var anotherChild = p.AddChild();
                var firstChildParent = firstChild.Parent;
                var anotherChildParent = anotherChild.Parent;
            }
        }
    }
    

相关问题