2017-08-03 71 views
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

+0

的可能的複製[測試對象是否是在C#中詞典(https://stackoverflow.com/questions/123181 /測試 - 如果一個對象是一個字典在C - 銳) – derape

+0

@derape - 區別是,我沒有一個實例。我有一個類型。另外,我已經知道如何檢查它是否可以從Dictionary中分配。我需要檢查它是否也有特定的密鑰。 – smoksnes

+0

您必須深入研究接口定義[通用參數](https://msdn.microsoft.com/en-us/library/system.type.getgenericarguments(v = vs.110).aspx) –

回答

3

你必須檢查的泛型類型和第一類型參數(TKey):

concreteType.GetInterfaces().Any(i => i.IsGenericType && 
    (i.GetGenericTypeDefinition() == typeof(IDictionary<,>)) && 
    typeof(Bar).IsAssignableFrom(i.GetGenericArguments()[0])); 
+0

即可。正是我在找什麼。 – smoksnes

相關問題