私は、タイプがディクショナリかどうかを判断する から来ています。そこにある答えのどれも私の問題を適切に解決していません。
ここでの最も近い答えはLukas Klusis によるものですが、IsDictionary(Type type)
方法を提供するには不十分です。彼の答えからインスピレーションを得て、その方法を次に示します。
private static Type[] dictionaryInterfaces =
{
typeof(IDictionary<,>),
typeof(System.Collections.IDictionary),
typeof(IReadOnlyDictionary<,>),
};
public static bool IsDictionary(Type type)
{
return dictionaryInterfaces
.Any(dictInterface =>
dictInterface == type || // 1
(type.IsGenericType && dictInterface == type.GetGenericTypeDefinition()) || // 2
type.GetInterfaces().Any(typeInterface => // 3
typeInterface == dictInterface ||
(typeInterface.IsGenericType && dictInterface == typeInterface.GetGenericTypeDefinition())));
}
// 1
住所public System.Collections.IDictionary MyProperty {get; set;}
// 2
住所public IDictionary<SomeObj, SomeObj> MyProperty {get; set;}
// 3
(つまり、2 番目の) は、タイプのいずれかを実装する.Any
シナリオに対応します。type
dictionaryInterfaces
他の回答の問題は、#3に対処していると仮定して、#1と#2に対処していないことです。プロパティのタイプを取得してチェックすることはおそらく一般的なシナリオではないため、これは理解できます。しかし、あなたが私のようで、そのシナリオがあなたのユースケースの一部である場合は、どうぞ!