c# - 在 C# 中使用 IsAssignableFrom 和 "is"关键字

标签 c# asp.net-mvc casting unity-container reflection

努力学习Unity ,我不断看到以下用于覆盖 MVC 中的 GetControllerInstance 的代码:

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

在我看来,这是一种相当复杂的基本写作方式

if(controllerType is IController) { ... }

我明白 isIsAssignableFrom 之间存在细微差别,即 IsAssignableFrom 不包括转换,但我正在努力了解这种差异在实际场景中的含义。

什么时候选择 IsAssignableFrom 而不是 is 是重要的?它会对 GetControllerExample 产生什么影响?

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

最佳答案

这不一样。

if(controllerType is IController)

总是计算为false,因为controllerType总是一个Type,而一个Type 永远不是 IController

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

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

关于c# - 在 C# 中使用 IsAssignableFrom 和 "is"关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3013694/

相关文章:

c# - 关于如何制作应用程序的建议/代码示例 "Cluster Aware"

asp.net-mvc - 不同形式的预编译会影响性能吗?

c++ - 不正确的类型转换 - 类型转换或未定义行为的使用

Java "extending"一个对象

C#加载带有嵌入图像的外部dll

javascript - 确认对话框未在 asp.net 中归档 itemCommand

json - 将 JSON 发布到 WebAPI2 函数

c# - 如何在 C# 中从数据读取器中转换为空 boolean 值?

c# - 在 C# 中将单个十六进制字符转换为其字节值

javascript - Ajax Post 请求 MVC