[英]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
. 您也可以将字典视为非通用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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.