【问题标题】:Retrieve Data in an ArrayList with C#使用 C# 检索 ArrayList 中的数据
【发布时间】:2014-08-17 18:44:09
【问题描述】:

我在使用 C# 从 ArrayList 集合中检索数据时遇到问题。我正在将一个类保存到一个 ArrayList 中。该代码用于保存数据,但我不知道如何编写代码来检索它。我以为 _serviceList [0]._displayName 会检索第一项,但它失败了。如何查看 ArrayList 中的所有项目?

谢谢。

class Service
{
  public string _displayName;
  public ServiceControllerStatus _status;

  public Service ()
  {
    _displayName = "";
    _status = ServiceControllerStatus.Stopped;
  }

  public Service (string displayName, ServiceControllerStatus status)
  {
    _displayName = displayName;
    _status = status;
  }
}

class Program
{
  public static ArrayList _serviceList = new ArrayList ();

  public Program ()
  {
    _serviceList = null;
  }

  static void Main (string [] args)
  {
    .
    .
    .

    _serviceList.Add (new Service (service.DisplayName, service.Status));
  }

  // The following code doesn't work.
  Console.WriteLine (_serviceList [0]._displayName);

【问题讨论】:

  • 我会避免在 C# 中使用 ArrayList,期间。相反,请使用您知道类型的通用列表:List<Service> services = new List<Service>();
  • 您忘记从列表中拆箱元素 ((您的元素类型)mylist[0]).somePropertyofTheElement="asdf";
  • 谢谢@VP。您认为 List 是比 ArrayList 更好的选择。 :)
  • 感谢@ETFovac。我也会试试这个解决方案。

标签: c# collections arraylist


【解决方案1】:

如果您正在使用 .Net 框架 2.0 或更高版本,请使用 List<T> 泛型,为 List 键入安全版本,只需更改 line

public static ArrayList _serviceList = new ArrayList ();

public static List<Service> _serviceList = new List<Service>();

会解决你的问题。

但是,如果您正在使用低于 2.0 的框架,那么您必须将对象显式转换为 Service,例如:

Console.WriteLine (((Service)_serviceList [0])._displayName);

因为ArrayList 将返回类型为object 而不是Service

【讨论】:

  • 谢谢@Habb。做到了。我可以使用以下方法检索数据:foreach (var s in _serviceList) Console.Write (s._displayName);
猜你喜欢
  • 2017-01-31
  • 1970-01-01
  • 2015-07-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-22
  • 1970-01-01
  • 2015-05-20
  • 2016-01-29
相关资源
最近更新 更多