【问题标题】:Accessing elements of a list in another class访问另一个类中列表的元素
【发布时间】:2019-07-19 16:02:53
【问题描述】:

假设我有类似以下的内容。

namespace BurgerMachine
{
public class BaseList{

    private static readonly List<Bases> bList = new List<Bases>() //might need to take off readonly
    {
        new Bases(){ BaseID=1, BaseName="Bun"},
        new Bases(){ BaseID=2, BaseName="SeededBun"}
    };
    public static List<Bases> GetList()
    {
        return bList;
    }
}
    public class Bases
    {
        public int BaseID { get; set; }
        public string BaseName { get; set; }
    }
}

现在我想从另一个类访问上述列表的元素,这对我当前的设置是否可行,还是我需要返回更多?

我见过一些人创建列表然后从另一个类添加但不尝试访问已经存在的元素的示例。如果确实存在这样的例子,请指出正确的方向。

第一次以这种方式使用列表,所以我不太确定自己在做什么。任何帮助都会很棒。如果需要更多信息,请询问。

【问题讨论】:

  • 你的 GetList 方法是 static (不确定你是否想要那个),所以我不确定问题出在哪里。拨打BaseList.GetList()有什么问题吗?
  • 您只向我们展示了一半的代码;您希望 使用 列表的代码看起来像什么?它是在列表上执行foreach,还是插入新项目,还是什么?
  • 就像约翰说的那样,只需使用var list = BaseList.GetList();,然后您就可以像在任何其他只读列表中一样访问列表中的元素。并且“回答”您的评论“可能需要以只读方式起飞”,仅当您想添加/删除元素时
  • @MindSwipe readonly 修饰符仅影响 bList 字段,不允许在字段初始化/构造函数后重新分配。无论readonly 修饰符如何,都可以向GetList() 返回的List&lt;Bases&gt; 添加元素。如果List&lt;Bases&gt;ReadOnlyCollection&lt;Bases&gt;,则无法添加或删除元素。
  • @Johnbot 哎呀,我的错,我写的时候还睡着了

标签: c# list class


【解决方案1】:

这里有几个实现返回列表的最佳方式。

带静态类

public class BaseListProvider
{
    public static readonly Bases Bun = new Bases() { BaseID = 1, BaseName = "Bun" };
    public static readonly Bases SeededBun = new Bases() { BaseID = 2, BaseName = "SeededBun" };

    public static IEnumerable<Bases> GetList()
    {
        return new[]
        {
            Bun,
            SeededBun
        };
    }
}

public class Bases
{
    public int BaseID { get; set; }
    public string BaseName { get; set; }
}

如果您使用依赖注入,该接口会很有帮助

public class BaseListProvider : IBaseListProvider
{
    public static readonly Bases Bun = new Bases() { BaseID = 1, BaseName = "Bun" };
    public static readonly Bases SeededBun = new Bases() { BaseID = 2, BaseName = "SeededBun" };

    public IEnumerable<Bases> GetList()
    {
        return new[]
        {
            Bun,
            SeededBun
        };
    }
}

public interface IBaseListProvider
{
    IEnumerable<Bases> GetList();
}

public class Bases
{
    public int BaseID { get; set; }
    public string BaseName { get; set; }
}

【讨论】:

  • 你是不是把本来可以很简单的事情复杂化了?
  • 完全同意 Rahul 的观点,而且你正在重写 OP 的代码,以至于它不再做同样的事情,你正在创建一个新的 Array(甚至不是 OP 如何询问的 List)调用方法的时间
【解决方案2】:

你可以像下面那样将列表设为public 成员,然后从任何你想要的地方访问它

public List<Bases> bList = new List<Bases>()
{
    new Bases(){ BaseID=1, BaseName="Bun"},
    new Bases(){ BaseID=2, BaseName="SeededBun"}
};

你现在可以访问说

var blist = new BaseList().bList;

使用您当前的设置(如已评论),为什么不能只调用静态方法说 BaseList.GetList()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 2013-03-20
    • 2013-05-24
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多