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

2018-12-31 09:29发布

This code:

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

returns null.

and I have in the usings:

using namespace.a.b;

Update:

The type exists, it's in a different class library, and i need to get it by string name.

标签: c# reflection
16条回答
像晚风撩人
2楼-- · 2018-12-31 10:01

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...)

查看更多
牵手、夕阳
3楼-- · 2018-12-31 10:01

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.

查看更多
流年柔荑漫光年
4楼-- · 2018-12-31 10:02

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);

As assemblyName you don't need to FullName, only the name without the Version, Culture and PublicKeyToken is required.

查看更多
回忆,回不去的记忆
5楼-- · 2018-12-31 10:03
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;
}
查看更多
登录 后发表回答