【问题标题】:Reflection of C# Types: GetType( "myType" ) vs typeof( myType ) behavior differs. Why?C# 类型的反映:GetType("myType") 与 typeof(myType) 行为不同。为什么?
【发布时间】:2013-05-30 14:39:00
【问题描述】:

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

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

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

【问题讨论】:

  • MyNameSpace.MyClass 是否已完全解析?
  • 是的,MyNameSpace 是我自己的命名空间,但与您在 using 语句中放入的内容相同,例如:MyNameSpace 只是 MyCompany.MyLibrary 或 System.Windows.Forms 的简写(例如)。
  • MyNameSpace 是否包含在另一个命名空间中?

标签: c# reflection typeof


【解决方案1】:

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"));

【讨论】:

  • 谢谢sirCodesAlot。运行时与编译时是我的问题的关键。也许我可以先使用反射来实例化该类。如果可行,我会尝试并返回。
【解决方案2】:

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

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

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

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

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

考虑:

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

【讨论】:

  • 谢谢。也许我的示例代码不清楚——我为 GetType 的参数使用了一个完全限定的类名——这就是“MyNameSpace”。
  • 很确定添加命名空间不足以完全限定类型。例如,“System.Windows.Forms.Form”不是完全限定类型。 “System.Windows.Forms.Form, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089”是完全限定的类型。如果要发现完全限定的类型字符串,请执行以下操作: typeof(YourTypeHere).AssemblyQualifiedName;
猜你喜欢
  • 1970-01-01
  • 2010-12-22
  • 1970-01-01
  • 1970-01-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-10
相关资源
最近更新 更多