4

我想检查一个值是否属于任何类型的 ObservableCollection 类型,或者不在 C# 中?

例如:我可以检查一个值是否为字符串类型,如下所示:

string value = "value to Check";
bool b = value.GetType().Equals(typeof(string));  // b =true

但是如果我需要检查一个值是否是 ObservableCollection,无论其构成类型如何,我该怎么做?

例如:

ObservableCollection<T> collection = new ObservableCollection<T>();

如果我这样检查

bool b = collection.GetType().Equals(typeof(ObservableCollection<>)); // b=false

如何检查该值是否为收藏?

4

4 回答 4

8

尝试

bool b = collection.GetType().IsGenericType &&
           collection.GetType().GetGenericTypeDefinition() == typeof(ObservableCollection<>);
于 2013-09-18T10:16:41.967 回答
3

你可以像这样检查它:

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

}
于 2013-09-18T10:17:52.637 回答
3

根据您的需要,您还可以检查它是否实现INotifyCollectionChanged.

if (someCollection is INotifyCollectionChanged observable)
    observable.CollectionChanged += CollectionChanged;
于 2018-03-17T03:54:48.403 回答
1

集合的类型是泛型的,您要测试该类型的泛型定义:

collection.GetType()
  .GetGenericTypeDefinition()
  .Equals(typeof(ObservableCollection<>))
于 2013-09-18T10:17:35.807 回答