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

问题描述

在学习Unity,我一直看到以下代码用于在 MVC 中覆盖 GetControllerInstance:

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

我很欣赏 isIsAssignableFrom 之间的细微差别,即 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 而不是 is 很重要?它会对 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 和一个 Type 永远不是 IController.

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

is 运算符用于检查实例是否与给定类型兼容.

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

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

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

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

05-17 20:17