检查某个类型是否是 Action 委托
我正在尝试检查给定类型是否是操作委托,无论参数数量如何。
以下代码是我知道如何执行此操作的唯一方法。
public static bool IsActionDelegate( this Type source )
{
return source == typeof( Action ) ||
source.IsOfGenericType( typeof( Action<> ) ) ||
source.IsOfGenericType( typeof( Action<,> ) ) ||
....
source.IsOfGenericType( typeof( Action<,,,,,,,,,,,,,,,> ) );
}
IsOfGenericType()
是我的另一个扩展方法,它执行它所说的操作,它检查类型是否是给定的泛型类型。
还有更好的建议吗?
I'm trying to check whether a given type is an action delegate, regardless of the amount of parameters.
The following code is the only way I know how to do this.
public static bool IsActionDelegate( this Type source )
{
return source == typeof( Action ) ||
source.IsOfGenericType( typeof( Action<> ) ) ||
source.IsOfGenericType( typeof( Action<,> ) ) ||
....
source.IsOfGenericType( typeof( Action<,,,,,,,,,,,,,,,> ) );
}
IsOfGenericType()
is another extension method of mine, which does what it says, it checks whether the type is of the given generic type.
Any better suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您紧随具有 void 返回类型的委托之后,您可以执行以下操作:
这不会区分
Action
和MethodInvoker
(或与此相关的其他 void 委托)尽管。正如其他答案所建议的,您可以检查类型名称,但这有点难闻;-)如果您能澄清您想要识别 Action 委托的原因,以了解哪种方法最有效,将会有所帮助。
If you are just after the delegates that have a void return type you could do the following:
This would not distinguish between
Action
andMethodInvoker
(or other void delegates for that matter) though. As other answers suggest you could examine the type name, but that kinda smells ;-)It would help if you could clarify for what reason you want to identify
Action
delegates, to see which approach would work best.这似乎有效:
示例:
单身和单身都是正确的。函数为假
This seems to work:
Example:
Single and dueces are true. func is false
这些是不同的类型,除了名称之外没有任何共同点。我能想到的唯一半合理的捷径:
当然不是万无一失的,但是任何在 System 命名空间中声明自己的类型的人都应该受到一些痛苦和折磨。
These are distinct types with nothing in common but their name. The only semi-reasonable shortcut I can think of:
Certainly not fail-safe, but whomever declares his own types in the System namespace deserves some pain and suffering.