在 ItemsSource 中获取 List 中对象的类型

Getting the type of the object inside List inside ItemsSource

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

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

而且我找不到关于此错误的任何信息。也搜索过,找不到任何东西。有没有办法做我想做的事?甚至,比直接获取类型更好的方法?

编辑:

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

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

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

你试过使用 typeof:

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

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

你想要:

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

... 这将检查类型是否 exactly List<Foo> 或:

if (DataGridType.ItemsSource is List<Foo>)

... 这将检查类型是否 可分配给 List<Foo>.

或者,如果您要在 if 正文中投射:

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