简体   繁体   中英

How to check if specific dictionary is of generic dictionary type in c#?

The generic dictionary is as follows:

public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>

And specific dictionaries can be as follows:

var container = new ConcurrentDictionary<string, Unit>();
var container = new ConcurrentDictionary<string, CustomUnitClass>();

So, how can I check if some dictionary is of generic dictionary type?

object obj = GetObj(); // obj is some of many dictionaries
if(obj is ?)

Thank you in advance.

You shouldn't, but if you really need it for some reason it is:

if (obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
    // It is a Dictionary<TKey, TValue>
}

or

if (obj is ConcurrentDictionary<string, CustomUnitClass>) {
    // It is a ConcurrentDictionary<string, CustomUsnitClass>
}
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>

is an 'open generic type', and you cannot have instances of open generic types.

However, if you want to know whether the given object is a dictionary which has generic type parameters, you can use reflection to determine that:

        var d1 = new Dictionary<int, string> ();

        var t = d1.GetType ();

        Console.WriteLine ("Generic? " + t.IsGenericType);

You can also treat the dictionary as a non-generic IDictionary . Of course, you loose all strong typing in this case:

var dictionary = obj as IDictionary;
if (dictionary != null)
{
    ICollection keys = dictionary.Keys;    
    ICollection values = dictionary.Values;
    // work with keys and values as a collection of objects
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM