我想检查一个值是否是任何类型的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
如何检查值是否为集合?
答案 0 :(得分:7)
尝试
bool b = collection.GetType().IsGenericType &&
collection.GetType().GetGenericTypeDefinition() == typeof(ObservableCollection<>);
答案 1 :(得分: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个接口。
因此,由于每个Collection<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;
...
};
}
答案 2 :(得分:2)
根据您的需要,您还可以检查它是否实现了INotifyCollectionChanged
。
if (someCollection is INotifyCollectionChanged observable)
observable.CollectionChanged += CollectionChanged;
答案 3 :(得分:1)
集合的类型是通用的,您要测试类型的通用定义:
collection.GetType()
.GetGenericTypeDefinition()
.Equals(typeof(ObservableCollection<>))