简体   繁体   English

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

[英]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. 问题是我在'type'变量上收到一个空引用异常。 GetData() and SA010.GetSA() are in the same namespace. GetData()和SA010.GetSA()位于同一名称空间中。

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. 您的主要问题是在使用GetType时需要指定SA010的完整命名空间。

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

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

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 它对我有用

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

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