gpt4 book ai didi

c# - 由于保护级别,无法在同一命名空间中为公共(public)类使用构造函数?

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:35 25 4
gpt4 key购买 nike

我目前正在尝试映射很多 channel ,因此为了方便起见,制作了一个可以包含 channel 属性的类和一个字典,它将 ID 映射到 channel 。字典在一个类中, channel 定义在它们自己的类中,但在同一个命名空间中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ParentId = System.String;
using ChildIds = System.Collections.Generic.List<int>;
using ChannelName = System.String;
using CatalogEntry = System.Tuple<System.String, System.Collections.Generic.List<int>, System.String>;


namespace example
{
public class ChannelHandler
{
public ChannelName channelname { get; set; }
public ParentId parentid { get; set; }
public ChildIds list_of_childs { get; set; }
public int id;

ChannelHandler(ChannelName name, int id)
{
this.channelname = name;
this.id = id;
}

ChannelHandler(ChannelName name, int id, ParentId parentid)
{
this.channelname = name;
this.id = id;
this.parentid = parentid;
}

}

public class Class1
{
private Dictionary<int?, ChannelHandler> dictionary = new Dictionary<int?, ChannelHandler>();
public void inser_into_dictionary(string path)
{
string[] separatingChars = { " " };
string[] splittedPath = path.Split(separatingChars, StringSplitOptions.RemoveEmptyEntries);
int parentId = 0;
ChannelName parentName = string.Empty;
foreach (string channel_id in splittedPath)
{

ChannelName name = channel_id.Split('_').ElementAt(0);
string id = channel_id.Split('_').ElementAt(1);
int int_id = 0;
if (int.TryParse(id, out int_id))
{
int_id = int.Parse(id);
}

Tuple<string, int> pair_of_channel_and_id = new Tuple<string, int>(name, int_id);
if (this.dictionary.ContainsKey(int_id))
{
// Key exist, meaning this is a parent.
// Child entry has to be updated.
parentId = int_id;
parentName = name;
}
else
{
if (parentId == 0)
{
ChannelHandler channel = new ChannelHandler(name, int_id); //ChannelHandler.ChannelHandler is inaccesible due to protection level.
this.dictionary.Add(int_id, channel);

}
}
}
}
}
}

我似乎无法创建对象 channel 因为该类的构造函数似乎由于保护级别而无法访问?但是什么保护级别——一切都是公开的?

最佳答案

它可能看起来像:

public class ChannelHandler
{
public ChannelName ChannelName { get; set; }
public ParentId ParentId { get; set; }
public List<ChildId> ChildIds { get; set; }
public int Id;

public ChannelHandler(ChannelName name, int id)
{
ChannelName = name;
Id = id;
}

public ChannelHandler(ChannelName name, int id, ParentId parentid)
{
ChannelName = name;
Id = id;
ParentId = parentid;
}

默认情况下,类的任何元素的访问级别都是private。您需要将构造函数设为 publicinternal 以便类本身可以从外部访问。如果你看这篇文章here它解释了访问修饰符如何影响代码的可访问性级别。

我所做的另一项更改是更改您的成员的大小写以满足 c# 编码约定。参见 here

关于c# - 由于保护级别,无法在同一命名空间中为公共(public)类使用构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51002697/

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