不确定如何解释这一点,所以我会尝试尽可能详细地说明。 我正在创建一个Net Library,我需要在 NetClient 类中给出一个部分,例如本例中的 Headers :
NetClient netClient = new NetClient("host", port);
netClient.Headers.Add("Name", "Value");
我认为这会有效,但它不会(在 NetClient 类的实例中根本看不到 Headers 类):
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;
}
}
答案 0 :(得分:2)
将一个类放在另一个类中并不能使它成为该类的实例成员(甚至是静态成员),它只会影响该类的命名和范围。
要获取实例成员,您需要该类的实际成员,例如属性是标题项列表:
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(...)
。
答案 1 :(得分:0)
尝试将其公开,因为默认情况下类是&#34;内部&#34;内部的成员/变量是私有的。
因此,基本思想是创建内部实例,以便初始化类,并在运行时创建对象。请不要复制粘贴,因为我没有使用VS来纠正。
我认为应该更像:
NetClient netClient = new NetClient(&#34; host&#34;,port); netClient.Headers = netclient.CreateObjHeaders(&#34; Name&#34;,&#34; Value&#34;);
命名空间NetLib { 类NetClient { public string Host {get; } public int Port {get; }
public NetClient(string host, int port)
{
this.Host = host;
this.Port = port;
}
public Headers CreateObjHeaders(string Name, string Value)
{
Headers objHeaders=new Headers("Name", "Value");
return objHeaders;
}
public class Headers
{
public Headers(string Name, string Value)
{
Header objHeader=new Header("Name", "Value");
}
public class Header
{
public string Name { get; }
public string Value { get; }
internal Header(string name, string value)
{
this.Name = name;
this.Value = value;
}
}
答案 2 :(得分:0)
以下代码是否会为您提供所需内容?
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)
{
Host = host;
Port = port;
Headers = new Headers();
}
}
public sealed class Headers : Dictionary<String, String>
{
}