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

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

    Try using the full type name that includes the assembly info, for example:

    string typeName = @"MyCompany.MyApp.MyDomain.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null";
    Type myClassType = Type.GetType(typeName);
    

    I had the same situation when I was using only the the namesspace.classname to get the type of a class in a different assembly and it would not work. Only worked when I included the assembly info in my type string as shown above.

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

    If it's a nested Type, you might be forgetting to transform a . to a +

    Regardless, typeof( T).FullName will tell you what you should be saying

    EDIT: BTW the usings (as I'm sure you know) are only directives to the compiler at compile time and cannot thus have any impact on the API call's success. (If you had project or assembly references, that could potentially have had influence - hence the information isnt useless, it just takes some filtering...)

    0 讨论(0)
  • 2020-11-22 03:46
    Dictionary<string, Type> typeCache;
    ...
    public static bool TryFindType(string typeName, out Type t) {
        lock (typeCache) {
            if (!typeCache.TryGetValue(typeName, out t)) {
                foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
                    t = a.GetType(typeName);
                    if (t != null)
                        break;
                }
                typeCache[typeName] = t; // perhaps null
            }
        }
        return t != null;
    }
    
    0 讨论(0)
  • 2020-11-22 03:52

    I cheated. Since the types I want to create (by name) are all in In a dll I control, I just put a static method in the dll in the assembly that takes a simple name, and calls type.GetType from that context and returns the result.

    The original purpose was so that the type could be specified by name in configuration data. I've since change the code so that the user specified a format to process. The format handler classes implement a interface that determines if the type can parse the specified format. I then use reflection to find types that implement the interface, and find one that handles the format. So now the configuration specifies a format name, a not a specific type. The reflection code can look at adjacent dlls and load, them so I have a sort poor man's plug-in architecture.

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