[ACCEPTED]-Avoid giving namespace name in Type.GetType()-types
Accepted answer
I've used a helper method that searches 6 all loaded Assemblys for a Type matching the specified 5 name. Even though in my code only one Type 4 result was expected it supports multiple. I 3 verify that only one result is returned 2 every time I used it and suggest you do 1 the same.
/// <summary>
/// Gets a all Type instances matching the specified class name with just non-namespace qualified class name.
/// </summary>
/// <param name="className">Name of the class sought.</param>
/// <returns>Types that have the class name specified. They may not be in the same namespace.</returns>
public static Type[] getTypeByName(string className)
{
List<Type> returnVal = new List<Type>();
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();
}
There is no need to complicate things.
AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.FirstOrDefault(t => t.Name == "MyTypeName");
Use 1 Where
instead of FirstOrDefault
to get all the results.
Simple Cached version
Do this once....
nameTypeLookup = typeof(AnyTypeWithin_SomeNamespace).Assembly
.DefinedTypes.Where(t => t.DeclaringType == null)
.ToDictionary(k => k.Name, v => v);
Usage 1 - lookup many times via dictionary
nameTypeLookup["TheClass"];
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.