简体   繁体   English

为什么是“ typeof(ISubController).IsAssignableFrom(value.GetType())”而不是“ value is ISubController”

[英]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. 以为我对is关键字和IsAssignableFrom方法之间的区别有了很好的了解,但是在MVC中研究SubController时,我遇到了一些代码,这些代码使我觉得也许我缺少了一些东西。 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语句看起来像是一个复杂的版本:

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. 另外,我以前已经了解到 typeof(T).IsValueType大约是x is ValueType三倍,所以我认为它们不会因这种复杂性而获得任何性能优势。

Is there some nuance that I'm missing here? 我在这里想念一些细微差别吗? I'd like to think the ASP.NET MVC guys know what they're doing. 我想认为ASP.NET MVC的人知道他们在做什么。

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. 我认为在该代码中不存在使用IsAssignableFrom的重要原因。 Just one option from few equivalent. 仅有的几种选择之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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