我想找到Enumerable
的类型。我的代码是这样的:
Type[] intLikeTypes = new[] { typeof(int), typeof(decimal), typeof(long), typeof(float) };
List<int> columnValue = new List<int>();
columnValue.Add(1);
columnValue.Add(2);
var listType = columnValue.GetType().GetGenericArguments()[0];
Type listGenericType = columnValue.GetType().GetGenericTypeDefinition();
if (listGenericType == typeof(List<>))
{
bool isInstanceOfTypeInt = (listType == typeof(int));
if (intLikeTypes.Any(x => x.IsInstanceOfType(listType)))
resColumnValue=preProcessValue(columnVal, false, false);
else if (listType is string)
resColumnValue=preProcessValue(columnVal, true, false);
}
当我使用bool isInstanceOfTypeInt = (listType == typeof(int))
时,isInstanceOfTypeInt
为true
。但是,if(intLikeTypes.Any(x => x.IsInstanceOfType(listType))
条件为false
。为什么x.IsInstanceOfType(listType)
无法正确找到实例?
顺便说一下,linq
命令适用于columnValue
以外的list<int>
类型。例如,它适用于int
类型。
答案 0 :(得分:2)
替换条件
if (intLikeTypes.Any(x => x.IsInstanceOfType(listType)))
与
if (intLikeType.Any(x => x == listType))
顺便说一句,条件
if (listGenericType == typeof(List<>))
总是被评估为true,我认为没有理由将其评估为false。
<强>更新强>
方法IsInstanceOfType
确定&#34;类型&#34;变量是特定类型,它不确定类型是否与另一种类型相同(代码正在执行的情况)
int s = 5;
bool test = typeof(int).IsInstanceOfType(s);
&#39;测试的价值&#39;变量将为true,因为s变量的类型是int
但以下代码将评估为false
Type intType = typeof(int);
bool test = typeof(int).IsInstanceOfType(intType);
这里的测试&#39;变量的值为&#39; false&#39;因为变量&#39; intType&#39;哪种类型&#34;类型&#34;不是int
这是此方法文档的一部分
返回值
类型:System.Boolean
如果当前Type位于由o表示的对象的继承层次结构中,或者当前Type是实现的接口,则为true。如果这些条件都不是这种情况,如果o为null,或者当前Type是开放泛型类型(即ContainsGenericParameters返回true),则返回false。
有关详细信息,请参阅此方法的文档。
https://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype(v=vs.110).aspx