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

前端 未结 16 1356
旧巷少年郎
旧巷少年郎 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:26

    Make sure that the comma is directly after the fully qualified name

    typeof(namespace.a.b.ClassName, AssemblyName)
    

    As this wont work

    typeof(namespace.a.b.ClassName ,AssemblyName)
    

    I was stumped for a few days on this one

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

    For me, a "+" was the key! This is my class(it is a nested one) :

    namespace PortalServices
    {
    public class PortalManagement : WebService
    {
        public class Merchant
        {}
    }
    }
    

    and this line of code worked:

    Type type = Type.GetType("PortalServices.PortalManagement+Merchant");
    
    0 讨论(0)
  • 2020-11-22 03:30

    if your class is not in current assambly you must give qualifiedName and this code shows how to get qualifiedname of class

    string qualifiedName = typeof(YourClass).AssemblyQualifiedName;
    

    and then you can get type with qualifiedName

    Type elementType = Type.GetType(qualifiedName);
    
    0 讨论(0)
  • 2020-11-22 03:30

    This solution above seems to be the best to me, but it didn't work for me, so I did it as follows:

    AssemblyName assemblyName = AssemblyName.GetAssemblyName(HttpContext.Current.Server.MapPath("~\\Bin\\AnotherAssembly.dll"));
    string typeAssemblyQualifiedName = string.Join(", ", "MyNamespace.MyType", assemblyName.FullName);
    
    Type myType = Type.GetType(typeAssemblyQualifiedName);
    

    The precondition is that you know the path of the assembly. In my case I know it because this is an assembly built from another internal project and its included in our project's bin folder.

    In case it matters I am using Visual Studio 2013, my target .NET is 4.0. This is an ASP.NET project, so I am getting absolute path via HttpContext. However, absolute path is not a requirement as it seems from MSDN on AssemblyQualifiedNames

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

    If the assembly is referenced and the Class visible :

    typeof(namespace.a.b.ClassName)
    

    GetType returns null because the type is not found, with typeof, the compiler may help you to find out the error.

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

    You can also get the type without assembly qualified name but with the dll name also, for example:

    Type myClassType = Type.GetType("TypeName,DllName");
    

    I had the same situation and it worked for me. I needed an object of type "DataModel.QueueObject" and had a reference to "DataModel" so I got the type as follows:

    Type type = Type.GetType("DataModel.QueueObject,DataModel");
    

    The second string after the comma is the reference name (dll name).

    0 讨论(0)
提交回复
热议问题