簡體   English   中英

如何確定類是否繼承Dictionary <,>

[英]How to determine if class inherits Dictionary<,>

我有

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable

而且我想檢查對象是否為SerializeableDictionary(任何通用類型)。

為此,我嘗試:

type == typeof(SerializableDictionary<,>)
or type.isSubclass()
or typeof(SerializableDictionary<,>).isAssigneableFrom(type)

沒有任何效果。 如何判斷類型是SerializableDictionary還是任何類型?

tnx!

var obj = new List<int>(); // new SerializableDictionary<string, int>();
var type = obj.GetType();

var dictType = typeof(SerializableDictionary<,>);
bool b = type.IsGenericType && 
         dictType.GetGenericArguments().Length == type.GetGenericArguments().Length &&
         type == dictType.MakeGenericType(type.GetGenericArguments());

我可能會創建一個接口ISerializableDictionary並讓SerializableDictionary<TKey, TValue>繼承自該接口。

public interface ISerializableDictionary : IDictionary
{
}

public class SerializableDictionary<TKey, TValue>
    : Dictionary<TKey, TValue>, IXmlSerializable, ISerializableDictionary

然后:

var res = dic is ISerializableDictionary;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM