简体   繁体   中英

Calling a static method of a class using reflection

I'm attempting to call a static class method via reflection and get its return value as follows:

private SA GetData()
{
    Type type = Type.GetType("SA010");

    Object obj = Activator.CreateInstance(type);

    MethodInfo methodInfo = type.GetMethod("GetSA");

    return (SA)methodInfo.Invoke(obj, null);
}

Here's the class and method I'm calling:

public class SA010
{
    public static SA GetSA()
    {
        //do stuff
        return SA.
    }
}

The problem is i receive a null reference exception on the 'type' variable. GetData() and SA010.GetSA() are in the same namespace.

Any ideas why i might get this error, something to do with it being static maybe?

Your main problem is you need to specify the full namespace of SA010 when using GetType.

Type type = Type.GetType("SomeNamespace.SA010");

However if you are not dynamicly generating the name a easier solution is use typeof , this does not require you to entire the namespace in if the type is already within scope.

Type type = typeof(SA010);

2nd issue you will run in to once you fix the type, if a method is static you don't create a instance of it, you just pass null in for the instance for the Invoke call.

private SA GetData()
{
    Type type = typeof(SA010);

    MethodInfo methodInfo = type.GetMethod("GetSA");

    return (SA)methodInfo.Invoke(null, null);
}

Try to use

Type type = typeof(SA010);

instead of

Type type = Type.GetType("SA010");

it worked for me

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