假设您有一个带有 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();
}
有人知道如何做到这一点吗?
最佳答案
如果您想知道该类型是否是通用的InstantFeedbackCollectionViewModel
,您可以使用以下代码:
bool isInstantFeedbackCollectionViewModel =
datagrid.ItemsSource.GetType().GetGenericTypeDefinition() ==
typeof(InstantFeedbackCollectionViewModel<,,>);
如果您想知道该类型是否继承自泛型 InstantFeedbackCollectionViewModel
,请参阅 Check if a class is derived from a generic class .
关于c# - 检查对象是否是具有多个类型参数的泛型类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33152919/