Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

c# - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

/// <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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...