Class 库命名空间层次结构不工作

Class Library Namespace Hierarchy Not Working

我正在尝试在我的 class 库中实现 C# 中使用的命名空间层次结构。这是我正在尝试做的事情:

namespace Parent
{
    namespace Child
    {
        Class ChildClass {  }
    }

    Class ParentClass {  }
}

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

要访问 ChildClass,必须 using Parent.Child。但是可以通过 using Parent.

访问 ParentClass

我可以不编译class库而是将cs文件添加到项目中来做到这一点。但是当我编译为 DLL 并将其添加为项目中的引用时,我无法访问子命名空间。

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

有没有办法在 C# 中实现这个?

我认为你的class不见了public;以下代码对我有用。

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

我会创作;

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

你期望的工作原理是什么。

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

ParentClass.cs

namespace Parent
{
    public class ParentClass{ }
}

ChildClass.cs

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

这似乎对我有用。

您正在嵌套 类 和名称空间,这一切看起来有点混乱。为什么不保持更扁平的命名空间结构并在 类 中进行嵌套呢?请记住,您不需要嵌套命名空间或 类 来维持父子关系。

阅读以下内容: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;
        }
    }
}