问题描述
而努力学习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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!