简体   繁体   中英

Reflection of C# Types: GetType( “myType” ) vs typeof( myType ) behavior differs. Why?

I would like to use reflection to get an assembly for a supplied namespace and type. I would prefer to supply these as strings. It is probably important to note that the namespace and type are defined in an assembly other than the one that is executing this code, but the executing code assembly does have a reference to that other assembly.

My question is why does the static GetType(string) method return null, while if I hard-code the namespace and class and use typeof() as in the if statement, I get the required result?

Here is the code:

   string fullClassName = "MyNameSpace.MyClass";
   Type t = Type.GetType( fullClassName  ); // this returns null!
   if ( t == null ) 
   {
      t = typeof(MyNameSpace.MyClass); // this returns a valid type!
   }

Thanks for any insights you may have...

GetType actually queries a specific assembly (at runtime ) for a type that might be defined within the assembly (Similar to new Object().GetType() ). typeof on the other hand is determined at compile time.

For example:

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

Read this C#.NET - Type.GetType("System.Windows.Forms.Form") returns null

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

requires that you pass in a fully qualified assembly type string (see answers from link above)

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

The compiler/runtime knows the type already becuase you've passed it in directly.

Consideration:

MyObject might exist as different things in different assemblies, therefore, why should Type.GetType() know which one your're talking about? - that is why you must pass in a fully qualified string - so then it knows exactly where to look and what to look for.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM