检查方法的兼容性与给定的代表? [英] Check compatibility of a method with a given Delegate?

查看:122
本文介绍了检查方法的兼容性与给定的代表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#code,我怎么检查,如果一个给定的方法可以再通过一个特定的委托类型psented $ P $?

In C# code, how do I check if a given method can be represented by a particular delegate type?

我第一次尝试的东西,以我的知识类型,大致为:

I first tried something, based on my Type knowledge, along the lines of:

// The delegate to test against.
void TargetDelegate(string msg);

// and...
var methodInfo = Type.GetMethod(..);  // obtain the MethodInfo instance. 
// try to test it 
typeof(TargetDelegate).IsAssignableFrom(methodInfo.GetType());

但只处理类型,而不是方法 - 它永远是假的

but that deals with only Types and not methods - it will always be false.

我倾向于相信答案就在 代表 的类型,但我就在整箱徘徊在这一点上。任何帮助将是AP preciated。

My inclination is to believe the answer lies in the Delegate Type, but I'm just wandering around the FCL at this point. Any help would be appreciated.

推荐答案

我想尝试:

Delegate.CreateDelegate(typeof(TargetDelegate), methodInfo, false) != null

这将尝试创建委托并返回null失败。如果返回null,它应该意味着委托无法创建。如果返回别的,委托必须确定。

This will try to create the delegate and return null on failure. If it return null, it should mean that the delegate was not able to be created. If it returns anything else, the delegate must be OK.

这篇关于检查方法的兼容性与给定的代表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆