本文介绍了IsAssignableFrom和&QUOT使用;是"关键字在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

而努力学习Unity,我不断看到下面的code在MVC覆盖 GetControllerInstance

 如果(!typeof运算(一个IController).IsAssignableFrom(controllerType)){...}

这似乎对我pretty的基本写作方法错综复杂

 如果(controllerType是一个IController){...}

我AP preciate有之间的细微差别是 IsAssignableFrom ,即 IsAssignableFrom 不包括投转换,但我在努力了解实际情况下这种差别的含义。

当它是imporantant选择 IsAssignableFrom ?这将使在什么区别 GetControllerExample

 如果(!typeof运算(一个IController).IsAssignableFrom(controllerType))
      抛出新的ArgumentException(...);
返回_container.Resolve(controllerType)作为一个IController;


解决方案

这是不一样的。

 如果(controllerType是一个IController)

总是的计算结果为,因为 controllerType 总是键入键入从来都不是一个IController

运算符是用来检查是否一个例如是给定类型兼容。

该IsAssignableFrom方法用于检查键入是否与给定类型兼容。

While trying to learn Unity, I keep seeing the following code for overriding GetControllerInstance in MVC:

if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }

this seems to me a pretty convoluted way of basically writing

if(controllerType is IController) { ... }

I appreciate there are subtle differences between is and IsAssignableFrom, ie IsAssignableFrom doesn't include cast conversions, but I'm struggling to understand the implication of this difference in practical scenarios.

When is it imporantant to choose IsAssignableFrom over is? What difference would it make in the GetControllerExample?

if (!typeof(IController).IsAssignableFrom(controllerType))
      throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;
解决方案

It's not the same.

if(controllerType is IController)

would always evaluate to false since controllerType is always a Type, and a Type is never an IController.

The is operator is used to check whether an instance is compatible to a given type.

The IsAssignableFrom method is used to check whether a Type is compatible with a given type.

这篇关于IsAssignableFrom和&QUOT使用;是"关键字在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 02:23