检查对象是否是ObservableCollection?

Abh*_*out 3 c# c#-4.0

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

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

string value = "value to Check";
bool b = value.GetType().Equals(typeof(string));  // b =true
Run Code Online (Sandbox Code Playgroud)

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

例如:

ObservableCollection<T> collection = new ObservableCollection<T>();
Run Code Online (Sandbox Code Playgroud)

如果我这样检查

bool b = collection.GetType().Equals(typeof(ObservableCollection<>)); // b=false
Run Code Online (Sandbox Code Playgroud)

如何检查值是否为集合?

dca*_*tro 8

尝试

bool b = collection.GetType().IsGenericType &&
           collection.GetType().GetGenericTypeDefinition() == typeof(ObservableCollection<>);
Run Code Online (Sandbox Code Playgroud)