c# - typeof(ICollection<>).GetTypeInfo().IsAssignableFrom(typeof(IList<>))

标签 c# portable-class-library reflection

我正在尝试检查以下内容

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/

相关文章:

c# - 计算数组数组中等于指定值的元素

c# - 在 SharePoint 2010 中复制或移动文档库

java - Java 中的抽象类和反射

c# - BouncyCaSTLe 未定义长度 ASN1

c# - 便携类 4.0 : Missing Features

c# - 在 .NET 中获取泛型类型的基本名称的正确方法是通过 Substring?

java - 获取 getDeclaredMethods() 以匹配可变参数方法

c# - 如何进行批量插入——Linq to Entities

c# - ASP NET 5 本地化在单独的程序集中使用 View 组件

visual-studio - 如何更改 Xamarin.Forms(可移植)应用程序中的 PCL 配置文件