delegate reflection

In this chapter you will learn:

  1. Create Delegate using reflection

Create Delegate using reflection

using System;/*  ja v  a2 s.com*/
using System.Reflection;
using System.Collections.Generic;

delegate void ComputeDelegate( Employee emp, Decimal percent );

public class Employee
{
    public Decimal Salary;

    public Employee( Decimal salary ) {
        this.Salary = salary;
    }

    public void ApplyRaiseOf( Decimal percent ) {
        Salary *= (1 + percent);
    }
}

public class MainClass
{
    static void Main() {
        List<Employee> employees = new List<Employee>();

        employees.Add( new Employee(20) );
        employees.Add( new Employee(50) );

        MethodInfo mi = typeof(Employee).GetMethod( "ApplyRaiseOf", BindingFlags.Public | BindingFlags.Instance );
        ComputeDelegate applyRaise = (ComputeDelegate ) Delegate.CreateDelegate( typeof(ComputeDelegate), mi );

        foreach( Employee e in employees ) {
            applyRaise( e, (Decimal) 0.10 );

            Console.WriteLine( e.Salary );
        }
    }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Get event from Type
Home » C# Tutorial » Reflection
Reflection
Type
Type properties
Field reflection
Field Type
Field Attributes
FieldHandle
Field value
Set Field value
delegate reflection
Event reflection
Indexer reflection
Properties Reflection
Method
Parameter
Invoke
Type Instantiating
interface reflection
Generic type reflection
Reflection on nested Types
Subtype
Array reflection
Assembly