Calling a static method of a class using reflectio

2019-07-05 00:23发布

问题:

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?

回答1:

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


回答2:

Try to use

Type type = typeof(SA010);

instead of

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

it worked for me



标签: c# reflection