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

问题描述 投票:0回答:2

例如,我们有以下代码,由Microsoft提供

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.'

c# methods reflection system.reflection methodinfo
2个回答
2
投票

如果你读了docs

typeName

要获取的类型的程序集限定名称。见AssemblyQualifiedName。如果类型在当前正在执行的程序集中或在Mscorlib.dll中,则提供由其名称空间限定的类型名称就足够了。

因此,当MagicClass包含在命名空间中时,您必须至少指定命名空间:

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

否则它将返回null


0
投票

如果名称空间位于同一名称空间中,则动态获取名称空间。

        string ns = typeof(TestMethodInfo).Namespace;
        Type magicType = Type.GetType(ns + ".MagicClass");
© www.soinside.com 2019 - 2024. All rights reserved.