5

我想使用反射来获取提供的命名空间和类型的程序集。我更愿意将这些作为字符串提供。可能需要注意的是,命名空间和类型是在一个程序集中定义的,不是在执行此代码的程序集中,但正在执行的代码程序集确实具有对该其他程序集的引用。

我的问题是为什么静态 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!
   }

感谢您提供的任何见解...

4

2 回答 2

15

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"));
于 2013-05-30T14:40:54.460 回答
1

阅读此C#.NET - Type.GetType("System.Windows.Forms.Form") 返回 null

Type t = Type.GetType("MyObject"); //null

要求您传入完全限定的程序集类型字符串(请参阅上面链接中的答案)

Type t = typeof(MyObject); //Type representing MyObject

编译器/运行时已经知道类型,因为您已直接将其传入。

考虑:

MyObject可能作为不同的东西存在于不同的程序集中,因此,为什么 Type.GetType() 应该知道你在说哪一个?- 这就是为什么你必须传入一个完全限定的字符串 - 这样它就确切地知道在哪里寻找和寻找什么。

于 2013-05-30T15:09:49.423 回答