jeudi 9 juillet 2015

Get the type with specified name in the different assemblies but the same namepsace

I need to get the type with specified class name which have the same namespace in the different assemblies.

For example:

Assembly1

namespace ABCSolution.MyProject.MyCode
{
    public class Class1
    {
    }
}

Assembly2

namespace ABCSolution.MyProject.MyCode
{
    public class Class2
    {
    }
}

In my cases, I don't know which assembly a specified class belongs to at runtime. So I am using the code below

private Type GetType(string typeName)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            assemblies = assemblies.Where(x => x.FullName.StartsWith("ABCSolution.MyProject.MyCode.", StringComparison.InvariantCulture)).ToArray();

            foreach (var assembly in assemblies)
            {
                Type type = Type.GetType(typeName + ", " + assembly);

                if (type != null)
                {
                    return type;
                }
            }

            return null;
        }

var myType = GetType("ABCSolution.MyProject.MyCode.Class1");

My solution works fine most of times, however sometimes a null value is returned. I am not sure what happened and if I am using the correct approach.





Aucun commentaire:

Enregistrer un commentaire