类内的 C# 命名空间?

标签 c# class namespaces

不知道如何解释这一点,所以我会尽量提供尽可能多的细节。
我正在制作一个网络图书馆,我需要为我的 分配一个部分网客类,如 标题在这个例子中:

NetClient netClient = new NetClient("host", port);
netClient.Headers.Add("Name", "Value");

我认为这会起作用,但它不起作用(在 NetClient 类的实例中根本看不到 header 类):
namespace NetLib
{
    class NetClient
    {
        public string Host { get; }
        public int Port { get; }

        public NetClient(string host, int port)
        {
            this.Host = host;
            this.Port = port;
        }

        class Headers
        {
            class Header
            {
                public string Name { get; }
                public string Value { get; }

                internal Header(string name, string value)
                {
                    this.Name = name;
                    this.Value = value;
                }
            }



我在提交的答案的帮助下解决了我的问题,这就是我的代码现在的样子:
   public sealed class NetClient
   {
        public string Host { get; set; }
        public int Port { get; set; }
        public Headers Headers { get; private set; }


        public NetClient(string host, int port)
        {
            this.Headers = new Headers();
            this.Host = host;
            this.Port = port;
        }
    }

    public sealed class Headers
    {
        public class Header
        {
            public string Name { get; }
            public string Value { get; }

            internal Header(string name, string value)
            {
                this.Name = name;
                this.Value = value;
            }
        }

最佳答案

将一个类放在另一个类中并不会使其成为该类的实例成员(甚至是静态成员),它只会影响该类的命名和范围。

要获取实例成员,您需要该类的实际成员,例如作为标题项列表的属性:

namespace NetLib {

  class Header {

    public string Name { get; }
    public string Value { get; }

    public Header(string name, string value) {
      this.Name = name;
      this.Value = value;
    }

  }

  class NetClient {

    public string Host { get; private set; }
    public int Port { get; private set; }
    public List<Header> Headers { get; private set; }

    public NetClient(string host, int port) {
      this.Host = host;
      this.Port = port;
      this.Headers = new List<Header>();
    }

  }

}

用法:
NetClient netClient = new NetClient("host", port);
netClient.Headers.Add(new Header("Name", "Value"));

你可以把 Header NetClient 里面的类类,但随后您需要使用 new NetClient.Header(...)而不是 new Header(...) .

关于类内的 C# 命名空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33597929/

相关文章:

c# - 是否有 CodeIgniter 等效的 ASP.NET?

c# - 如何找到所有 Controller 和 Action

c# - 从给定日期计算月份的星期几?

Swift 通过 Init 传递多个参数

php - 保存外部 xml 文件的副本,而不使用 xml 命名空间

c# - 有 powerpoint 演示吗?

class - 我如何在 Puppet 中执行类

c++ - 如何从 C++ 调用 JNI DLL

javascript - 为什么我不能在 jQuery(document).ready() 中调用我的 namespace ?

c++ - 实现或定义在未命名/匿名命名空间内声明的类或函数