Ste*_*e L 5 c# reflection typeof
我想使用反射来获取提供的命名空间和类型的程序集.我更愿意将它们作为字符串提供.需要注意的是空间和类型在装配中定义这可能是重要的其他比正在执行这段代码的人,但执行代码程序集确实有一个参考给其他组件.
我的问题是为什么静态GetType(string)方法返回null,而如果我硬编码命名空间和类并使用if语句中的typeof(),我得到所需的结果?
这是代码:
string fullClassName = "MyNameSpace.MyClass";
Type t = Type.GetType( fullClassName ); // this returns null!
if ( t == null )
{
t = typeof(MyNameSpace.MyClass); // this returns a valid type!
}
Run Code Online (Sandbox Code Playgroud)
感谢您的任何见解......
sir*_*lot 14
GetType实际上查询特定程序集(在运行时)以查找可能在程序集中定义的类型(类似于new Object().GetType()).typeof另一方面是在编译时确定的.
例如:
// Nonsense. "Control" is not in the same assembly as "String"
Console.WriteLine(typeof(String).Assembly.GetType("System.Windows.Controls.Control"));
// This works though because "Control" is in the same assembly as "Window"
Console.WriteLine(typeof(Window).Assembly.GetType("System.Windows.Controls.Control"));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14969 次 |
| 最近记录: |