我正在尝试检查以下内容
typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( targetProperty.PropertyType.GetTypeInfo() )
参数传递给 IsAssignableFrom
的地方是一个 IList<Something>
.但它返回 false。
以下也返回 false。
typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( targetProperty.PropertyType.GetTypeInfo().GetGenericTypeDefinition() )
即使是以下内容也返回 false。
typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( typeof(IList<>) )
后者不应该返回 true 吗?
当 targetProperty.PropertyType
时,我怎样才能得到正确的结果?可以是任何类型吗?它可能是 List<T>
, 一个 ObservableCollection<T>
, 一个 ReadOnlyCollection<T>
、自定义集合类型等。
最佳答案
您有两个开放的通用类型。 IsAssignableFrom
将这些解释为询问是否 ICollection<T1>
可从 IList<T2>
分配.一般来说,这是错误的。仅当 T1 = T2 时为真。您需要做一些事情来关闭具有相同类型参数的泛型类型。您可以将类型填写为object
或者您可以获得通用参数类型并使用它:
var genericT = typeof(ICollection<>).GetGenericArguments()[0]; // a generic type parameter, T.
bool result = typeof(ICollection<>).MakeGenericType(genericT).IsAssignableFrom(typeof(IList<>).MakeGenericType(genericT)); // willl be true.
好像GetGenericArguments
在 PCL 中不可用,其行为不同于 GenericTypeArguments
属性(property)。在 PCL 中,您需要使用 GenericTypeParameters
:
var genericT = typeof(ICollection<>).GetTypeInfo().GenericTypeParameters[0]; // a generic type parameter, T.
bool result = typeof(ICollection<>).MakeGenericType(genericT).GetTypeInfo().IsAssignableFrom(typeof(IList<>).MakeGenericType(genericT).GetTypeInfo()); // willl be true.
关于c# - typeof(ICollection<>).GetTypeInfo().IsAssignableFrom(typeof(IList<>)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18937119/