To dynamically instantiate a delegate, call Delegate.CreateDelegate
.
The following example demonstrates instantiating both an instance delegate and a static delegate:
using System;
using System.Reflection;
using System.Collections.Generic;
class Program
{
delegate int IntFunc(int x);
static int Square(int x) { return x * x; } // Static method
int Cube (int x) { return x * x * x; } // Instance method
static void Main()
{
Delegate staticD = Delegate.CreateDelegate(typeof(IntFunc), typeof(Program), "Square");
Delegate instanceD = Delegate.CreateDelegate
(typeof(IntFunc), new Program(), "Cube");
Console.WriteLine(staticD.DynamicInvoke(3)); // 9
Console.WriteLine(instanceD.DynamicInvoke(3)); // 27
}
}
The output:
9
27
java2s.com | Contact Us | Privacy Policy |
Copyright 2009 - 12 Demo Source and Support. All rights reserved. |
All other trademarks are property of their respective owners. |