2
我正在處理自定義JsonConverter
,並覆蓋CanConvert
-方法。檢測它是否是詞典,並且鍵可以從特定類型分配
public override bool CanConvert(Type objectType)
{
return (typeof(IDictionary).IsAssignableFrom(objectType) ||
TypeImplementsGenericInterface(objectType, typeof(IDictionary<,>)));
}
private static bool TypeImplementsGenericInterface(Type concreteType, Type interfaceType)
{
return concreteType.GetInterfaces()
.Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == interfaceType);
}
非常受啓發this answer。問題是如果字典的鍵是特定類型的,我只想返回true
。例如,如果密鑰類型爲Bar
,或者繼承/實現Bar
,我只想返回true。價值並不重要。該值可以是任何類型。
Dictionary<string, int> // false
Dictionary<Bar, string> // true
Dictionary<Foo, string> // false
Dictionary<Bar, Foo> // true
Dictionary<BarSubClass, Foo> // true
我怎樣才能從Type
,發現如果它是一個Dictionary
關鍵是分配從一個特定的類型?
我試過到目前爲止:
typeof(IDictionary<Bar, object>).IsAssignableFrom(objectType)
不幸的是這將返回false
。
的可能的複製[測試對象是否是在C#中詞典(https://stackoverflow.com/questions/123181 /測試 - 如果一個對象是一個字典在C - 銳) – derape
@derape - 區別是,我沒有一個實例。我有一個類型。另外,我已經知道如何檢查它是否可以從Dictionary中分配。我需要檢查它是否也有特定的密鑰。 – smoksnes
您必須深入研究接口定義[通用參數](https://msdn.microsoft.com/en-us/library/system.type.getgenericarguments(v = vs.110).aspx) –