I want to get all methods from class through reflection and assign them to created delegate or instantiate new delegete with them.
I am trying to learn reflection and delegates and I want to use reflection here because I don't like the way it look like with +=
I tried to assign with Delegate.CreateDelegate method but there isn't any overloads that get array of MethodInfo which I get from reflection.
public delegate void GetIntegersPower(int x);
class Program
{
static void Main(string[] args)
{
GetIntegersPower iP = Power.Square;
iP += Power.Cubed;
iP += Power.xToThePowerOfFour;
iP += Power.xToThePowerOfFive;
iP += Power.xToThePowerOfSix;
var powerMembers = typeof(Power).GetMethods();
var del=(Action<int>)Delegate.CreateDelegate(typeof(Action<int>), powerMembers[0]); //error
del(3);
Console.ReadKey();
}
}
class Power
{
public static void Square(int x) => Console.WriteLine($"The number of {x} to the power of two equals {x * x}" + Environment.NewLine);
public static void Cubed(int x) => Console.WriteLine($"The number of {x} to the power of three equals {x * x * x}" + Environment.NewLine);
public static void xToThePowerOfFour(int x) => Console.WriteLine($"The number of {x} to the power of four equals {x * x * x * x}" + Environment.NewLine);
public static void xToThePowerOfFive(int x) => Console.WriteLine($"The number of {x} to the power of five equals {x * x * x * x * x}" + Environment.NewLine);
public static void xToThePowerOfSix(int x) => Console.WriteLine($"The number of {x} to the power of six equals {x * x * x * x * x * x}" + Environment.NewLine);
}
Now I am able only to execute one method when I supply to MethodInfo index but I want to create multicast delegate
Aucun commentaire:
Enregistrer un commentaire