简体   繁体   中英

Why “typeof(ISubController).IsAssignableFrom(value.GetType())” instead of “value is ISubController”

I thought I had a pretty good grasp of the difference between the is keyword and the IsAssignableFrom method, but researching SubControllers in MVC I ran across some code that made me think maybe there's something I'm missing. Here it is:

object value = pair.Value;
if(value == null)
{
    continue;
}

if (typeof(ISubController).IsAssignableFrom(value.GetType()))
{
    var controller = (ISubController) value;
    filterContext.Controller.ViewData.Add(pair.Key, controller.GetResult(filterContext.Controller));
}

That second if statement looks to me like a convoluted version of:

if (value is ISubController)

Also, I had previously learned that typeof(T).IsValueType takes about three times as long as x is ValueType , so I don't think they're getting any performance advantage out of this added complication.

Is there some nuance that I'm missing here? I'd like to think the ASP.NET MVC guys know what they're doing.

That code can be rewritten even as following:

var controller = value as ISubController;
if (controller != null)
    filterContext.Controller.ViewData.Add(pair.Key, controller.GetResult(filterContext.Controller));

I don't think important reason exists for using IsAssignableFrom in that code. Just one option from few equivalent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM