繁体   English   中英

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

[英]Calling a static method of a class using 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);
}

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

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

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

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

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

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

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

Type type = typeof(SA010);

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

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

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

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

尝试使用

Type type = typeof(SA010);

代替

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

它对我有用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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