获取ItemsSource中List中对象的类型

本文关键字:类型 对象 List ItemsSource 获取 | 更新日期: 2023-09-27 18:05:40

我有一个DataGrid,它是一个列表,它可以是类型Foo, Bar或Baz。稍后,我需要提取该数据以保存它,为此,我需要知道设置为ItemsSource的List中对象的类型。我已经尝试使用GetType,没有工作,尝试做if(GridType is List<Foo>)例如产生以下警告:

The given expression is never of the provided ('System.Collections.Generic.List<Foo>') type

我在这个错误上找不到任何东西。我也找了,什么也没找到。有什么方法可以做我想做的事吗?或者有比直接获取类型更好的方法吗?

编辑:

忽略所有锅炉板代码(使用etc..)

假设我们已经创建了一个DataGrid,稍后将其添加到窗口

public class Foo
{
  public int SomeVar { get; set; }
}
public class MainWindow : Window
{
  public MainWindow ()
  {
  List<Foo> Foos = new List<Foo> ();
  Foos.Add (new Foo ());
  Foos.Add (new Foo ());
  DataGrid SomeDataGrid = new DataGrid ();
  SomeDataGrid.ItemsSource = Foos;
  Type DataGridType = SomeDataGrid.ItemsSource.GetType ();
  if (DataGridType is List<Foo>) //< Error 
    {
    // do stuff
    }
  }
}

获取ItemsSource中List中对象的类型

您正在混合两件事- is检查对象是否属于给定类型,而GetType()返回Type引用。DataGridType的类型是Type,而Type对象永远不是List<Foo>的实例。(想象一下将DataGridType转换为List<Foo> -这意味着什么?)

您需要:

if (DataGridType == typeof(List<Foo>))

…它将检查类型是否完全是 List<Foo>或:

if (DataGridType.ItemsSource is List<Foo>)

…它将检查类型是否可分配给 List<Foo>

或者,如果您想在if体中强制转换:

List<Foo> listFoo = DataGridType.ItemsSource as List<Foo>;
if (listFoo != null)
{
    // Use listFoo
}

你有没有试过使用typeof:

if(GridType == typeof(List<Foo>))