【问题标题】:Storing an array of structs in GlobalVariables.cs in C#在 C# 中的 GlobalVariables.cs 中存储结构数组
【发布时间】:2016-08-20 07:47:02
【问题描述】:

我有一个结构数组。如何将它们全局存储在 GlobalVariables.cs 中?当我尝试时,它会给出一个错误,指出由于其保护级别而无法访问。请帮忙!

这是 GlobalVariables.cs 代码:

public class GlobalVariables
    {
       List<Employee[]> persons = new List<Employee[]>();
    }

表格代码如下:

List<Employee> persons = new List<Employee>()
{
    new Employee { Name = "alfred", Id = 203476, Authority = "1" },
    new Employee { Name = "barbara", Id = 182856, Authority = "4" },
    new Employee { Name = "chris", Id = 398046, Authority = "2" },
};

这是员工结构:

public struct Employee
    {       
        public string Name;
        public int Id;
        public string Authority;
    }

【问题讨论】:

  • Employee 结构是否在内部类中声明为嵌套类型?

标签: c# arrays struct


【解决方案1】:

我不确定您的代码要做什么,但是如果您将 GlobalVariables 设为静态类(公共静态类 GlobalVariables),然后像 GlobalVariables.persons 从其他类一样访问它,事情应该没问题.如果这不起作用,请尝试多解释一下您想对您的代码做什么。

public static class GlobalVariables
{
   public static List<Employee[]> persons = new List<Employee[]>();

//静态类的字段如果从其他类访问,需要是静态的和公共的 }

然后(来自另一个班级):

Employee person = new Employee();
GlobalVariables.persons.Add(person);

编辑:哎呀-刚刚注意到您的全局列表是数组列表,因此您将添加 person[] 而不是 person。不知道您为什么要这样做,但上面的代码通过使用公共静态回答了您的全局访问问题。

顺便说一句,使用

List<Employee>

会比

容易得多
List<Employee[]> 

用于大多数用途。如果需要,您可以随时使用

之类的方法对列表进行分组
GlobalVariables.persons.Where(p=>p.Authority=="2");

如果您真的需要对员工进行分组,最好使用全局 Dictionary 而不是数组列表。

【讨论】:

  • 正是我所追求的。非常感谢。
猜你喜欢
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-29
  • 1970-01-01
相关资源
最近更新 更多