Jak utworzyć pełnomocnika z MethodInfo, gdy podpis metody nie może być wcześniej znany?
Potrzebuję metody, która zajmujeMethodInfo
instancja reprezentująca nietypową metodę statyczną z dowolną sygnaturą i zwraca delegata powiązanego z tą metodą, który może być później wywołany przy użyciuDelegate.DynamicInvoke
metoda. Moja pierwsza naiwna próba wyglądała tak:
using System;
using System.Reflection;
class Program
{
static void Main()
{
var method = CreateDelegate(typeof (Console).GetMethod("WriteLine", new[] {typeof (string)}));
method.DynamicInvoke("Hello world");
}
static Delegate CreateDelegate(MethodInfo method)
{
if (method == null)
{
throw new ArgumentNullException("method");
}
if (!method.IsStatic)
{
throw new ArgumentNullException("method", "The provided method is not static.");
}
if (method.ContainsGenericParameters)
{
throw new ArgumentException("The provided method contains unassigned generic type parameters.");
}
return method.CreateDelegate(typeof(Delegate)); // This does not work: System.ArgumentException: Type must derive from Delegate.
}
}
Miałem nadzieję, żeMethodInfo.CreateDelegate
metoda może określić właściwy typ delegata. Cóż, oczywiście nie może. Jak więc utworzyć instancjęSystem.Type
reprezentowanie delegata z podpisem pasującym do podanegoMethodInfo
instancja?