开发者

Comparing base types in reflection

I am calling a method on an assembly using reflection and I need to first compare if one of the parameters for the method has the same base type with the parameter I am passing in for it.

But whenever I call passedInParameter.GetType().BaseType() it returns "

{Name = "开发者_运维问答MarshalByRefObject" FullName = "System.MarshalByRefObject"}.

Shouldn't it be showing the interface it is implementing?


The runtime has helpers for this:

if (typeof(ISomeInterface).IsAssignableFrom(passedInParameter.GetType()))
{
}

Backgrounder:

Interfaces are not basetypes. CLR types cannot have multiple base types.

You should be able to enumerate interfaces implemented by a type, but as you can see from my proposed solution, I don't recommend doing all that


Interface is not a base class. Class may implement a lot of interfaces If you want to get list of interfaces just use

passedInParameter.GetType().GetInterfaces();

also you can try to use is operator

if(passedInParameter is ISomeInterface)
{
    // do some logic
}

Try to use this code snippet

    ParameterInfo param = paramList[i]; 
    Type type = paramArray[i].GetType();

    bool valid = false;
    if (info.ParameterType.IsInterface)
        valid = type.GetInterfaces().Contains(param.ParameterType);
    else
        valid = type.IsSubclassOf(param.ParameterType);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜