使用反射调用类的静态方法

Dan*_*all 3 c# reflection

我试图通过反射调用静态类方法并获取其返回值,如下所示:

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

    Object obj = Activator.CreateInstance(type);

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

    return (SA)methodInfo.Invoke(obj, null);
}
Run Code Online (Sandbox Code Playgroud)

这是我正在调用的类和方法:

public class SA010
{
    public static SA GetSA()
    {
        //do stuff
        return SA.
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我在'type'变量上收到一个空引用异常.GetData()和SA010.GetSA()位于同一名称空间中.

任何想法为什么我可能会得到这个错误,这与它是静态的可能吗?

Sco*_*ain 7

您的主要问题是在使用GetType时需要指定SA010的完整命名空间.

Type type = Type.GetType("SomeNamespace.SA010");
Run Code Online (Sandbox Code Playgroud)

但是,如果您没有动态生成名称,则使用更简单的解决方案typeof,如果类型已在范围内,则不需要整个命名空间.

Type type = typeof(SA010);
Run Code Online (Sandbox Code Playgroud)

第二个问题,你将在修复类型后运行,如果方法是静态的,你不创建它的实例,你只需传入调用null的实例Invoke.

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

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

    return (SA)methodInfo.Invoke(null, null);
}
Run Code Online (Sandbox Code Playgroud)