Type.GetType("TheClass");
Returns null if the namespace is not present like:
Type.GetType("SomeNamespace.TheClass"); // returns a Type object
Is there any way to avoid giving the namespace name?
解决方案
I've used a helper method that searches all loaded Assemblys for a Type matching the specified name. Even though in my code only one Type result was expected it supports multiple. I verify that only one result is returned every time I used it and suggest you do the same.
///
/// Gets a all Type instances matching the specified class name with just non-namespace qualified class name.
///
/// Name of the class sought.
/// Types that have the class name specified. They may not be in the same namespace.
public static Type[] getTypeByName(string className)
{
List returnVal = new List();
foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
{
Type[] assemblyTypes = a.GetTypes();
for (int j = 0; j < assemblyTypes.Length; j++)
{
if (assemblyTypes[j].Name == className)
{
returnVal.Add(assemblyTypes[j]);
}
}
}
return returnVal.ToArray();
}