0

通用字典如下:

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 ?)

先感谢您。

4

3 回答 3

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>
}
于 2012-05-30T12:31:41.573 回答
0
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>

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

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

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

        var t = d1.GetType ();

        Console.WriteLine ("Generic? " + t.IsGenericType);
于 2012-05-30T12:34:06.120 回答
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
}
于 2012-05-30T13:25:33.950 回答