2

How do I check if an object I receive as a method result is not ValueType and not IEnumerable<ValueType>?

Here is what I wrote:

MethodInfo selectedOverload = SelectOverload(selectedMethodOverloads);
object result = ExecuteAndShowResult(selectedOverload);
ExploreResult(result);

private static void ExploreResult(object result)
{
 if (result != null &&
     !(result is ValueType) &&
     !((IEnumerable)result).GetType().GetProperty("Item").PropertyType) is ValueType)
    )
    Console.WriteLine("explore");
}

Unfortunately type of PropertyType is Type, its content is the type I need to check (e.g. int) but I don't know how to.

EDIT:

Ok, the .IsValueType worked, but now I want also to exclude strings (which are not recognized as ValueTypes), so what?

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType is string)

doesn't work!

EDIT 2:

Just answered myself:

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType == typeof(string))

The question remains open about what if I want to check the inheritance from a base class:

!(((IEnumerable)result).GetType().GetProperty("Item").PropertyType == typeof(BaseClass))

doesn't work because typeof checks runtime type, and if PropertyType == InheritedClassType it will return false...

4

1 回答 1

4

使用Type.IsValueType

private static void ExploreResult(object result)
{
 if (result != null &&
     !(result.GetType().IsValueType) &&
     !((IEnumerable)result).GetType().GetProperty("Item").PropertyType.IsValueType)
    )
    Console.WriteLine("explore");
}

虽然 ifresult不是值类型但不是IEnumerablethan 你会得到一个强制转换错误。该检查需要一些工作。

回答第二部分

!((IEnumerable)result).GetType().GetProperty("Item").PropertyType is string)

始终为 false,因为PropertyType返回的 aType绝不是字符串。我想你想要

!(result.GetType().GetProperty("Item").PropertyType == typeof(string))

请注意,我取出演员表,IEnumerable因为无论如何您都是通过反射寻找属性,所以演员表是无关紧要的。

回答第三次编辑

我想检查基类的继承

为此你想要type.IsAssignableFrom()

Type itemType = result.GetType().GetProperty("Item").PropertyType;
bool isInheritedFromBaseClass = 
    typeof(BaseClass).IsAssignableFrom(itemType);
于 2013-10-02T14:35:34.913 回答