typeof(IEnumerable <object>)。IsAssignableFrom(typeof(IEnumerable <int>))为false

时间:2019-06-04 21:55:39

标签: c# .net-core system.reflection

为什么typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<int>))为假,但typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>))为假 是真的吗?

我尝试了很多这种变化(请参见代码)。

此代码适用于我尝试过的每个类,但int作为通用类型除外。

property.PropertyType == typeof(string)
//false
property.PropertyType == typeof(IEnumerable<int>)
//true
typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType)
//false
typeof(IEnumerable<int>).IsAssignableFrom(property.PropertyType)
//true
typeof(object).IsAssignableFrom(typeof(string))
//true
typeof(object).IsAssignableFrom(typeof(int))
//true
//check that object is assignable from int
typeof(object).IsAssignableFrom(property.PropertyType.GenericTypeArguments[0])
//true
typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<int>))
//false
typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<string>))
//true
//maybe it only works for string lets try a list of a list of strings
typeof(IEnumerable<object>).IsAssignableFrom(typeof(IEnumerable<List<int>>))
//true
//Maybe type a specific List not just iEnumerable
typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<int>))
//false
//Does string still work?
typeof(IEnumerable<object>).IsAssignableFrom(typeof(List<string>))
//true

//try getType for no reason
var intList = new List<int>();
var intListType = intList.GetType();
intListType
//{Name = "List`1" FullName = "System.Collections.Generic.List`1[[System.Int32, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]"}
typeof(IEnumerable<int>).IsAssignableFrom(intListType)
//true
typeof(IEnumerable<object>).IsAssignableFrom(intListType)
//false

0 个答案:

没有答案