【问题标题】:Check if object is of generic type with multiple type arguments检查对象是否属于具有多个类型参数的泛型类型
【发布时间】:2016-01-14 04:04:55
【问题描述】:

假设您有一个带有 ItemsSource-Property (DataGrid.ItemsSource) 的网格。此属性是在运行时设置的。可能的对象如下:

public partial class InstantFeedbackCollectionViewModel<TEntity, TPrimaryKey, TUnitOfWork> 
   : InstantFeedbackCollectionViewModelBase<TEntity, TEntity, TPrimaryKey, TUnitOfWork>

稍后在运行时我想捕获一个事件并想检查网格的 ItemsSource 是否属于上述类型。

通常我会这样做:

if (typeof(datagrid.ItemsSource) is InstantFeedbackCollectionViewModel) then ...

但是我怎样才能用这个泛型类做到这一点呢?

更新:

在第二步中,我想在 InstantFeedbackCollectionViewModel 中执行一个方法。类似的东西:

if (datagrid.ItemsSource.GetType().GetGenericTypeDefinition() == typeof(InstantFeedbackCollectionViewModel<,,>) {
var instFeedbackCollectionViewModel = grid.ItemsSource;
instFeedbackCollectionViewModel.ExecuteMyMethod();
}

有人知道怎么做吗?

【问题讨论】:

    标签: c# .net class generics typeof


    【解决方案1】:

    如果您想知道该类型是否为泛型InstantFeedbackCollectionViewModel,您可以使用以下代码:

    bool isInstantFeedbackCollectionViewModel = 
          datagrid.ItemsSource.GetType().GetGenericTypeDefinition() ==
          typeof(InstantFeedbackCollectionViewModel<,,>);
    

    如果您想知道该类型是否继承自泛型InstantFeedbackCollectionViewModel,请参阅Check if a class is derived from a generic class

    【讨论】:

    • 这正是我在第一步中想要的。
    • 是的。您对我的附加问题也有想法吗?
    • @SaschaR,定义一个接口 IInstantFeedbackCollectionViewModel 公开适当的方法。从 InstantFeedbackCollectionViewModel 实现它,然后尝试将 ItemSource 转换为此接口。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-09-12
    • 2022-01-26
    • 2013-03-04
    • 2018-05-15
    • 2016-11-24
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多