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 09:41

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

查看更多
倾城一夜雪
3楼-- · 2018-12-31 09:41

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.

查看更多
步步皆殇っ
4楼-- · 2018-12-31 09:41

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();
查看更多
零度萤火
5楼-- · 2018-12-31 09:42

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.

查看更多
与君花间醉酒
6楼-- · 2018-12-31 09:42

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.

查看更多
公子世无双
7楼-- · 2018-12-31 09:44

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

查看更多
登录 后发表回答