Type.GetType(“namespace.a.b.ClassName”) returns null

前端 未结 16 1343
旧巷少年郎
旧巷少年郎 2020-11-22 02:58

This code:

Type.GetType(\"namespace.a.b.ClassName\")

returns null.

and I have in the usings:

using nam         


        
相关标签:
16条回答
  • 2020-11-22 03:33

    I am opening user controls depending on what user controls the user have access to specified in a database. So I used this method to get the TypeName...

    Dim strType As String = GetType(Namespace.ClassName).AssemblyQualifiedName.ToString
    Dim obj As UserControl = Activator.CreateInstance(Type.GetType(strType))
    

    So now one can use the value returned in strType to create an instance of that object.

    0 讨论(0)
  • 2020-11-22 03:36

    Try this method.

    public static Type GetType(string typeName)
    {
        var type = Type.GetType(typeName);
        if (type != null) return type;
        foreach (var a in AppDomain.CurrentDomain.GetAssemblies())
        {
            type = a.GetType(typeName);
            if (type != null)
                return type;
        }
        return null;
    }
    
    0 讨论(0)
  • 2020-11-22 03:37

    Type.GetType("namespace.qualified.TypeName") only works when the type is found in either mscorlib.dll or the currently executing assembly.

    If neither of those things are true, you'll need an assembly-qualified name:

    Type.GetType("namespace.qualified.TypeName, Assembly.Name")
    
    0 讨论(0)
  • 2020-11-22 03:37

    When I have only the class name I use this:

    Type obj = AppDomain.CurrentDomain.GetAssemblies().SelectMany(t => t.GetTypes()).Where(t => String.Equals(t.Name, _viewModelName, StringComparison.Ordinal)).First();
    
    0 讨论(0)
  • 2020-11-22 03:39

    As Type.GetType(String) need the Type.AssemblyQualifiedName you should use Assembly.CreateQualifiedName(String, String).

    string typeName = "MyNamespace.MyClass"; // Type.FullName
    string assemblyName = "MyAssemblyName"; // MyAssembly.FullName or MyAssembly.GetName().Name
    string assemblyQualifiedName = Assembly.CreateQualifiedName(assemblyName , typeName);
    Type myClassType = Type.GetType(assemblyQualifiedName);
    

    The Version, Culture and PublicKeyToken are not required for assemblyName that's why you can use MyAssembly.GetName().Name.

    About Type.GetType(String) :

    If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

    0 讨论(0)
  • 2020-11-22 03:43

    If the assembly is part of the build of an ASP.NET application, you can use the BuildManager class:

    using System.Web.Compilation
    ...
    BuildManager.GetType(typeName, false);
    
    0 讨论(0)
提交回复
热议问题