简体   繁体   中英

Type.getType() can't find the class

I have a lot of static methods in a class, I want to get if a certain method is in the class X, and if it is, I want to invoke it. I checked with this:

if (Type.GetType("Homework.Homework.Functions").GetMethod(methodName) == null)
            {
                Console.WriteLine("No such method.\nPress any key to restart the program");
                Console.ReadKey();
                Console.Clear();
                Main();
                return;
            }
            else
                Type.GetType("Homework.Homework.Functions").GetMethod(methodName).Invoke(null, parametersArray); // Invoking the method.

But it gives me a System.NullReferenceException in the line with the if() in it.

The starting of the program:

namespace Homework
{
class Homework
{
    static void Main()
    {

Declaration of the class:

public class Functions
    {

I probably should say that the class Functions is inside the class Homework.

How do I solve this error?

Thanks.

The problem is that nested types are separated with a + rather than a . in the IL name. If you write:

Console.WriteLine(typeof(global::Homework.Homework.Functions));

then you'll see the fully qualified name as far as the CLR is concerned.

So you want:

Type.GetType("Homework.Homework+Functions")

Assuming you really need to get it by name - avoid this sort of thing where possible. Use typeof wherever you know the type at compile-time (and are happy to have a reference if it's in a different assembly).

That will work if you're calling it from within the same assembly. If you're calling Type.GetType from a different assembly, you'll need to qualify the name with the assembly as well.

I'd also strongly encourage you not to name a class the same as its namespace .

You need to specify an assembly qualified name to GetType(string) . Instantiate your Homework class and look at its

GetType().FullName 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM