我想使用反射为提供的命名空间和类型获取程序集。我更愿意将这些作为字符串提供。可能很重要的一点是,命名空间和类型是在执行此代码的程序集其他中定义的,但执行代码程序集确实有一个引用那个另一个集会。
我的问题是为什么静态 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!
}
感谢您提供的任何见解...
最佳答案
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"));
关于c# - C# 类型的反射 : GetType( "myType" ) vs typeof( myType ) behavior differs. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16839081/