Ste*_*ris 7 c# reflection delegates
我试图检查给定类型是否是一个动作委托,无论参数数量多少.
以下代码是我知道如何执行此操作的唯一方法.
public static bool IsActionDelegate( this Type source )
{
return source == typeof( Action ) ||
source.IsOfGenericType( typeof( Action<> ) ) ||
source.IsOfGenericType( typeof( Action<,> ) ) ||
....
source.IsOfGenericType( typeof( Action<,,,,,,,,,,,,,,,> ) );
}
Run Code Online (Sandbox Code Playgroud)
IsOfGenericType()
是我的另一种扩展方法,它执行它所说的,它检查类型是否是给定的泛型类型.
有更好的建议吗?
如果您只是在具有void返回类型的代理之后,您可以执行以下操作:
public static bool IsActionDelegate(Type sourceType)
{
if(sourceType.IsSubclassOf(typeof(MulticastDelegate)) &&
sourceType.GetMethod("Invoke").ReturnType == typeof(void))
return true;
return false;
}
Run Code Online (Sandbox Code Playgroud)
但是,这不会区分Action
和MethodInvoker
(或其他无效代表).正如其他答案建议您可以检查类型名称,但有点气味;-)如果您可以澄清您想要识别Action
代表的原因,看看哪种方法最有效,这将有所帮助.
归档时间: |
|
查看次数: |
2192 次 |
最近记录: |