【问题标题】:Add ListView objects to an array将 ListView 对象添加到数组
【发布时间】:2014-06-24 03:45:52
【问题描述】:

有没有办法将 ListView 对象添加到数组中,以便我可以使用 for 循环快速处理它们?

    public static ListView tagListView;
    public static ListView commonListView;
    public static ListView recentListView;
    public static ListView[] listviews = { tagListView, commonListView, recentListView };

此代码导致 listviews 数组项为空。我已经尝试了一些变化,结果相同。这可能吗?看来我只需要创建一个指向这三个对象的指针数组。

我正在尝试这样做,因为 ListViews 在大多数情况下都非常不同,并且拥有名称使其比仅在数组中包含三个项目更具可读性,但每隔一段时间我需要做同样的事情这三个。

【问题讨论】:

  • 您尚未实例化要添加到数组中的三个变量。这就是为什么他们是null

标签: c# arrays object


【解决方案1】:

你几乎明白了。您只需要实例化 ListViews。

   public static ListView tagListView = new ListView();
   public static ListView commonListView = new ListView();
   public static ListView recentListView = new ListView();
   public static ListView[] listviews = { tagListView, commonListView, recentListView };

【讨论】:

  • 好的,抱歉,我没有提到这三个 ListView 在我的代码的不同部分分配给我表单上的实际 ListView。
  • 你能显示你正在处理的问题的代码吗?
【解决方案2】:

您的代码实际上是这样的:

public static ListView tagListView = null;
public static ListView commonListView = null;
public static ListView recentListView = null;

所以你的数组赋值确实是这样的:

public static ListView[] listviews = { null, null, null};

如果您可以先实例化三个列表视图,那将是您最好的方法。

但是,如果您不能这样做并且需要稍后在代码中实例化它们,那么还有另一种方法。

你可以这样做:

public static IEnumerable<ListView> listviews = (new Func<ListView>[]
{
    () => tagListView,
    () => commonListView,
    () => recentListView,
}).Select(x => x()).Where(x => x != null);

现在您有一个可枚举的实例化列表视图,在您迭代可枚举时

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-13
    • 2018-09-06
    • 1970-01-01
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    相关资源
    最近更新 更多