fea*_*net 51 c# reflection asp.net-mvc casting unity-container
在尝试学习Unity时,我一直看到以下代码覆盖GetControllerInstanceMVC:
if(!typeof(IController).IsAssignableFrom(controllerType)) { ... }
Run Code Online (Sandbox Code Playgroud)
在我看来,这基本上是一种非常复杂的写作方式
if(controllerType is IController) { ... }
Run Code Online (Sandbox Code Playgroud)
我理解,存在之间的细微差别is和IsAssignableFrom,即IsAssignableFrom不包括投转换,但我在努力了解实际情况下这种差别的含义.
什么时候选择IsAssignableFrom结束有意义is?它会有什么不同GetControllerExample?
if (!typeof(IController).IsAssignableFrom(controllerType))
throw new ArgumentException(...);
return _container.Resolve(controllerType) as IController;
Run Code Online (Sandbox Code Playgroud)
Mar*_*ann 80
这是不一样的.
if(controllerType is IController)
Run Code Online (Sandbox Code Playgroud)
将始终评估为false,因为controllerType始终是一个Type,并且Type是永远的IController.
该is操作被用来检查是否实例是给定类型兼容.
IsAssignableFrom方法用于检查Type是否与给定类型兼容.
thi*_*eek 16
is 关键字仅适用于实例,而Type.IsAssignableFrom()仅适用于类型.
的例子 is
string str = "hello world";
if(str is String)
{
//str instance is of type String
}
Run Code Online (Sandbox Code Playgroud)
请注意,str是一个实例,而不是类型.
的例子 IsAssignableFrom()
string str = "hello world";
if(typeof(Object).IsAssignableFrom(str.GetType()))
{
//instances of type String can be assigned to instances of type Object.
}
if(typeof(Object).IsAssignableFrom(typeof(string)))
{
//instances of type String can be assigned to instances of type Object.
}
Run Code Online (Sandbox Code Playgroud)
请注意,IsAssignableFrom()的参数不是String的实例,它是表示String类型的Type对象.
一个值得注意的差异是'is'对于测试继承或接口实现具有直观意义,而IsAssignableFrom在表面上做出任何有意义的事情.应用于测试继承或检测接口实现时,Type.IsAssignableFrom方法的名称含糊不清且令人困惑.以下用于这些目的的包装器将提供更直观,可读的应用程序代码:
public static bool CanBeTreatedAsType(this Type CurrentType, Type TypeToCompareWith)
{
// Always return false if either Type is null
if (CurrentType == null || TypeToCompareWith == null)
return false;
// Return the result of the assignability test
return TypeToCompareWith.IsAssignableFrom(CurrentType);
}
Run Code Online (Sandbox Code Playgroud)
然后,可以有更易理解的客户端语法,如:
bool CanBeTreatedAs = typeof(SimpleChildClass).CanBeTreatedAsType(typeof(SimpleClass));
CanBeTreatedAs = typeof(SimpleClass).CanBeTreatedAsType(typeof(IDisposable));
Run Code Online (Sandbox Code Playgroud)
此方法的优点是代替'is'关键字,它可以在运行时用于测试未知的任意类型,而'is'关键字(和通用的Type参数)需要特定类型的编译时知识.
| 归档时间: |
|
| 查看次数: |
14190 次 |
| 最近记录: |