C# 将ListView对象添加到数组

C# 将ListView对象添加到数组,c#,arrays,object,C#,Arrays,Object,有没有一种方法可以将ListView对象添加到数组中,以便我可以使用for循环快速寻址它们 public static ListView tagListView; public static ListView commonListView; public static ListView recentListView; public static ListView[] listviews = { tagListView, commonListView, recent

有没有一种方法可以将ListView对象添加到数组中,以便我可以使用for循环快速寻址它们

    public static ListView tagListView;
    public static ListView commonListView;
    public static ListView recentListView;
    public static ListView[] listviews = { tagListView, commonListView, recentListView };
此代码导致ListView数组项为空。我已经尝试过这种方法的一些变体,但效果相同。这可能吗?看起来我只需要创建一个指向这三个对象的指针数组


我之所以这么做,是因为ListView在很大程度上是非常不同的,拥有名称比在一个数组中拥有三个项目更具可读性,但每隔一段时间,我就需要对所有三个项目执行相同的操作。

您几乎可以做到这一点。您只需要实例化ListView

   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 };

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

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);
公共静态IEnumerable ListView=(新函数[]
{
()=>tagListView,
()=>commonListView,
()=>recentListView,
}).Select(x=>x())。其中(x=>x!=null);

现在,在迭代可枚举项时,您有了实例化列表视图的可枚举项。

您还没有实例化要添加到数组中的三个变量。这就是为什么它们是
null
。好的,对不起,我没有提到这三个ListView是在我的代码的不同部分分配给我表单上的实际ListView的。你能显示你正在处理的问题的代码吗?