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

问题描述

在尝试学习,我一直看到以下代码覆盖 GetControllerInstance 在MVC:

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) { ... }

code>是和 IsAssignableFrom ,即 IsAssignableFrom ,但我很难理解这种差异对实际情况的影响。

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.

何时是重要的选择 IsAssignableFrom ?在 GetControllerExample

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;


推荐答案

不一样。

if(controllerType is IController)

总是评估 false ,因为 controllerType 总是 Type ,并且类型从不是 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.

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

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

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

07-02 04:30