Как я могу создать делегата Действия из MethodInfo?

Я хочу получить делегата действия от объекта MethodInfo. Действительно ли это возможно?

36
задан Carlo V. Dango 14 August 2019 в 06:13
поделиться

1 ответ

Используйте Delegate.CreateDelegate :

// Static method
Action action = (Action) Delegate.CreateDelegate(typeof(Action), method);

// Instance method (on "target")
Action action = (Action) Delegate.CreateDelegate(typeof(Action), target, method);

Для Action и т. Д. Просто укажите везде соответствующий тип делегата.

В .NET Core Delegate.CreateDelegate не существует, но MethodInfo.CreateDelegate существует:

// Static method
Action action = (Action) method.CreateDelegate(typeof(Action));

// Instance method (on "target")
Action action = (Action) method.CreateDelegate(typeof(Action), target);
63
ответ дан 27 November 2019 в 05:53
поделиться
Другие вопросы по тегам:

Похожие вопросы: