[英]C# How to make Dictionary<Type,Generic<Type>>?
[英]How to check if specific dictionary is of generic dictionary type in c#?
通用字典如下:
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 ?)
先感謝您。
您不應該這樣做,但是如果出於某些原因您確實需要它,那就是:
if (obj.GetType().GetGenericTypeDefinition() == typeof(Dictionary<,>)) {
// It is a Dictionary<TKey, TValue>
}
要么
if (obj is ConcurrentDictionary<string, CustomUnitClass>) {
// It is a ConcurrentDictionary<string, CustomUsnitClass>
}
public class ConcurrentDictionary<TKey, TValue> : IDictionary<TKey, TValue>
是“開放通用類型”,您不能有開放通用類型的實例。
但是,如果您想知道給定的對象是否是具有通用類型參數的字典,則可以使用反射來確定:
var d1 = new Dictionary<int, string> ();
var t = d1.GetType ();
Console.WriteLine ("Generic? " + t.IsGenericType);
您也可以將字典視為非通用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.