How to reflection check nullable object is IDictionary
eg:
if object is not null it can use is
keyword to check.
void Main()
{
Dictionary<string, object> v = new Dictionary<string,object>();
Console.WriteLine(CheckValueIsIDictionary(v)); //true
}
bool CheckValueIsIDictionary(object value){
return value is IDictionary;
}
but if parameter value is null then will get false
void Main()
{
Dictionary<string, object> v = null;
Console.WriteLine(CheckValueIsIDictionary(v)); //false
}
bool CheckValueIsIDictionary(object value){
return value is IDictionary;
}
I expect get true
result, thanks!
update:
I want to check value declare type is a IDictionary
before example you can know this null value is from Dictionary<string,object>
and this type is a IDictionary
and I want to get the relationship result.
and why I'd like to do it:
I want to check values is IDictionary or not to do different logic, object value can be Array or Dictionary<int,int> or List
You can only do this with type inference and generics:
public static bool CheckValueIsIDictionary<T>(T value)
{
Type typeT = typeof(T);
return value is IDictionary || typeof(IDictionary).IsAssignableFrom(typeof(T));
}
Obviously if you have something like this, you'll get false
:
Dictionary<string, string> myDictionary = null;
object o = myDictionary;
Console.WriteLine(CheckValueIsIDictionary(o));
But it will work where there is a value, or where the type is known at compile time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.