【问题标题】:C# Problems acessing protected List from child class从子类访问受保护列表的 C# 问题
【发布时间】:2018-03-21 12:17:57
【问题描述】:

我以为我可以从子类访问父类中的受保护列表,但得到错误

如果类型为“Liste”,则无法通过限定符访问受保护成员“Liste.listItems”,限定符必须为“ListReader”类型

知道如何克服这个问题,同时仍然保持受保护的List<Object> listItems 的保护级别(这样除了继承的类之外没有其他类可以访问这个列表)?

 public class Liste
{
    public string name;
    protected List<Object> listItems = new List<Object>(); //TO DO: add protection
}

class ListReader : Liste
{

    public List<Liste> listsRead = new List<Liste>();

    public List<Liste> ReadLists(TestCaseWorkbook tcwb, string tab)
    {
        try
        {
            int lineID = 0;
            foreach (DataRow row in tcwb.Tables[tab].Rows)
            {
                if (lineID == 0)//first line
                {
                    foreach (DataColumn cell in tcwb.Tables[tab].Columns)
                    {
                        Liste liste = new Liste();
                        liste.name = ExcelWorkbook.CleanTitleToInternal(cell.ColumnName);
                        if(liste.name != "")
                        {
                            listsRead.Add(liste);
                        }                                                   
                    }
                    lineID++;
                }                 
                for (int j = 0; j < row.ItemArray.Length; j++)//rest of sheet
                {
                    Object item = row[j];
                    if(item.ToString() != "")
                    {
                        listsRead[j].listItems.Add(item);
                    }
                }                    
            }

(更多代码)

问题出在listsRead[j].listItems.Add(item);

【问题讨论】:

  • 请将其缩减为minimal reproducible example。我强烈怀疑这里 90% 的代码是无关紧要的,但是您没有准确地显示错误的在哪里minimal reproducible example 会更容易为您提供帮助。
  • 请贴出相关错误详情。
  • 您访问的不是同一个实例的成员,而是列表中的树结构中其他对象的成员列表Read[j].listItems。

标签: c# inheritance protected


【解决方案1】:

您使字段受保护,因此您无权在新类实例中设置它。我猜你只需要保护二传手,所以改变这个

protected List<Object> listItems = new List<Object>();

进入

public List<Object> listItems { get; protected set; } = new List<Object>();

如果你既不使用“name”也不使用“listItems”,则不需要从 Liste 继承

【讨论】:

    猜你喜欢
    • 2017-01-12
    • 2012-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-18
    • 2013-12-22
    • 2012-11-25
    • 2010-09-16
    • 1970-01-01
    相关资源
    最近更新 更多