gpt4 book ai didi

类内的 C# 命名空间?

转载 作者:行者123 更新时间:2023-12-04 16:53:21 34 4
gpt4 key购买 nike

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

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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com