你可以像这样检查它:
public static bool IsObservableCollection(object candidate) {
if (null == candidate) return false;
var theType = candidate.GetType();
bool itIs = theType.IsGenericType() &&
!theType.IsGenericTypeDefinition()) &&
(theType.GetGenericTypeDefinition() == typeof(ObservableCollection<>));
return itIs;
}
您还可以获得元素类型:
public static Type GetObservableCollectionElement(object candidate) {
bool isObservableCollection = IsObservableCollection(candidate);
if (!isObservableCollection) return null;
var elementType = candidate.GetType().GetGenericArguments()[0];
return elementType;
}
编辑
实际上以动态方式使用 ObservableCollection 有点棘手。如果您查看ObservableCollection<T>
课程:
ObservableCollection<T> : Collection<T>, INotifyCollectionChanged, INotifyPropertyChanged
您会注意到它扩展Collection<T>
并实现了 2 个接口。
因此,由于 everyCollection<T>
也是非泛型的IEnumerable
,您可以像这样推断动态已知的 ObservableCollection:
object someObject = ...
bool itsAnObservableCollection = IsObservableCollection(someObject);
if (itsAnObservableCollection) {
IEnumerable elements = someObject as IEnumerable;
// and try to reason about the elements in this manner
foreach (var element in elements) { ... }
INotifyCollectionChanged asCC = someObject as INotifyCollectionChanged;
INotifyPropertyChanged asPC = someObject as INotifyPropertyChanged;
// and try to let yourself receive notifications in this manner
asCC.CollectionChanged += (sender, e) => {
var newItems = e.NewItems;
var oldItems = e.OldItems;
...
};
asPC.PropertyChanged += (sender, e) => {
var propertyName = e.PropertyName;
...
};
}