Hi,
If we call the method as below, str = "System.Diagnostics.Debug" t = Type.GetType(str, true, true);
We will get error as below, because the Type.GetType method will only search the current assembly which called the method. System.TypeLoadException: Could not load type 'System.Diagnostics.Debug' from assembly 'TestTraceDe****, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. at System.RuntimeTypeHandle._GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark, Boolean loadTypeFromPartialName) at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) at System.RuntimeType.PrivateGetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark) at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
So we need to use Assembly.GetType approach to do that. Because we did not know which assembly the type may locate, we can enumerate all the assembly in current appdomain.
static void Main(string[] args) { string str ="System.Diagnostics.Debug"; Type t=null; Debug.WriteLine("Test"); //This line is necessary, or the System.dll will not loaded, so the "System.Diagnostics.Debug" will not be found. try { Assembly[] myAssemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly myAssembly in myAssemblies) { Console.WriteLine(myAssembly.CodeBase.ToString()); t = myAssembly.GetType(str); if (null != t) break; } } catch (Exception e) { Console.WriteLine(e.ToString()); }
if (null != t) Console.WriteLine(t.Namespace.ToString()); }
If you still have any concern, please feel free to post here.
Best regards, Peter Huang
|