简体   繁体   中英

Avoid giving namespace name in Type.GetType()

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 Assembly s 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.

/// <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 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 - lookup many times via dictionary

nameTypeLookup["TheClass"];

That's the parameter the method expect to get, so no. You can not.

typeName: type name qualified by its namespace.

MSDN

How do you expect to distinguish between two classes with the same name but different Namespace?

namespace one
{
    public class TheClass
    {
    }
}

namespace two
{
    public class TheClass
    {
    }
}

Type.GetType("TheClass") // Which?!

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