typeof(ICollection<>).GetTypeInfo().IsAssignableFrom(typeof(IList<>))) [英] typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( typeof(IList<>) )

查看:85
本文介绍了typeof(ICollection<>).GetTypeInfo().IsAssignableFrom(typeof(IList<>)))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检查以下内容

I am trying to check the following

typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( targetProperty.PropertyType.GetTypeInfo() )

传递给IsAssignableFrom的参数是IList<Something>.但是它返回的是假.

where the argument passed into IsAssignableFrom is an IList<Something>. But it is returning false.

以下内容还返回false.

The following also returns false.

typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( targetProperty.PropertyType.GetTypeInfo().GetGenericTypeDefinition() )

即使以下内容返回false.

Even the following is returning false.

typeof( ICollection<> ).GetTypeInfo().IsAssignableFrom( typeof(IList<>) )

后者肯定不会返回true吗?

Shouldn't the latter definitely return true?

targetProperty.PropertyType可以是任何类型时,如何获得正确的结果?可以是List<T>ObservableCollection<T>ReadOnlyCollection<T>,自定义集合类型等.

How can I get the correct result when targetProperty.PropertyType can be any type at all? It could be a List<T>, an ObservableCollection<T>, a ReadOnlyCollection<T>, a custom collection type, etc.

推荐答案

您有两种开放的通用类型. IsAssignableFrom解释这些就像询问是否可以从IList<T2>分配ICollection<T1>一样.通常,这是错误的.仅当T1 = T2时才成立.您需要执行一些操作以使用相同的type参数关闭通用类型.您可以将类型填写为object,也可以获取通用参数类型并使用该类型:

You have two open generic types. IsAssignableFrom interprets these like asking whether ICollection<T1> is assignable from IList<T2>. This is, in general, false. It is only true when T1 = T2. You need to do something to close the generic types with the same type argument. You could fill in the type as object or you could get the generic parameter type and use that:

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属性.在PCL中,您需要使用GenericTypeParameters:

It seems GetGenericArguments is not available in PCL, and its behavior is different than GenericTypeArguments property. In a PCL you need to use 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.

这篇关于typeof(ICollection&lt;&gt;).GetTypeInfo().IsAssignableFrom(typeof(IList&lt;&gt;)))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆