Invokes the method or constructor represented by the current instance, using the specified parameters in CSharp

Description

The following code shows how to invokes the method or constructor represented by the current instance, using the specified parameters.

Example


using System;//from   w  ww  . j a  v a2 s .c  o m
using System.Reflection;

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()
    {
        Type magicType = Type.GetType("MagicClass");
        ConstructorInfo magicConstructor = magicType.GetConstructor(Type.EmptyTypes);
        object magicClassObject = magicConstructor.Invoke(new object[]{});

        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 code above generates the following result.





















Home »
  C# Tutorial »
    Reflection »




Array
Constructor
Event
Field
Interface
Method
Properties
Type