如何从命名空间内部正确使用 GetMethod?

How to properly use GetMethod from inside a namespace?

比如我们有下面的代码,微软给的

public class MagicClass
{
    private int magicBaseValue;

    public MagicClass()
    {
        magicBaseValue = 9;
    }

    public int ItsMagic(int preMagic)
    {
        return preMagic * magicBaseValue;
    }
}

public class TestMethodInfo
{
    public static void Main()
    {
        // Get the constructor and create an instance of MagicClass

        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        // Get the ItsMagic method and invoke with a parameter value of 100

        MethodInfo magicMethod = magicType.GetMethod("ItsMagic");
        object magicValue = magicMethod.Invoke(magicClassObject, new object[]{100});

        Console.WriteLine("MethodInfo.Invoke() Example\n");
        Console.WriteLine("MagicClass.ItsMagic() returned: {0}", magicValue);
    }
}

// The example program gives the following output:
//
// MethodInfo.Invoke() Example
//
// MagicClass.ItsMagic() returned: 900

MethodInfo magicMethod = magicType.GetMethod("ItsMagic"); 如果我们将整个代码片段包含在我们选择的任何名称空间中,程序就会中断。

它抛出的异常如下: System.NullReferenceException: 'Object reference not set to an instance of an object.'

如果您阅读 docs:

typeName

The assembly-qualified name of the type to get. See AssemblyQualifiedName. If the type is in the currently executing assembly or in Mscorlib.dll, it is sufficient to supply the type name qualified by its namespace.

所以你必须至少指定命名空间,当MagicClass包含在命名空间中时:

Type magicType = Type.GetType("YourNameSpace.MagicClass");

否则会returnnull.

如果在同一命名空间中,则动态获取命名空间。

        string ns = typeof(TestMethodInfo).Namespace;
        Type magicType = Type.GetType(ns + ".MagicClass");