如何检查特定字典是否是c#中的通用字典类型?

时间:2012-05-30 12:28:56

标签: c# dictionary

通用字典如下:

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

具体词典可以如下:

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

那么,我如何检查某些字典是否属于通用字典类型?

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

提前谢谢。

3 个答案:

答案 0 :(得分:3)

你不应该,但如果你因某种原因真的需要它,那就是:

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

if (obj is ConcurrentDictionary<string, CustomUnitClass>) {
    // It is a ConcurrentDictionary<string, CustomUsnitClass>
}

答案 1 :(得分:0)

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

是一个“开放泛型类型”,您不能拥有开放泛型类型的实例。

但是,如果您想知道给定对象是否是具有泛型类型参数的字典,您可以使用反射来确定:

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

        var t = d1.GetType ();

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

答案 2 :(得分:0)

您还可以将字典视为非通用IDictionary。当然,在这种情况下你放弃了所有强类型:

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
}