如何检查一个对象是否具有某些方法/属性?
也许使用动态模式?您可以使用动态关键字调用任何方法/属性,对吧?例如,如何在调用 myDynamicObject.DoStuff() 之前检查该方法是否存在?
Using dynamic pattern perhaps? You can call any method/property using the dynamic keyword, right? How to check whether the method exist before calling myDynamicObject.DoStuff(), for example?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以写这样的东西:
编辑:你甚至可以做一个扩展方法并像这样使用它
You could write something like that :
Edit : you can even do an extension method and use it like this
通过反射
类似的是方法
via Reflection
Similar is for methods
这是一个老问题,但我刚刚遇到它。
如果有多个具有该名称的方法,
Type.GetMethod(string name)
将抛出 AmbigeousMatchException,因此我们最好处理这种情况It is an old question, but I just ran into it.
Type.GetMethod(string name)
will throw an AmbiguousMatchException if there is more than one method with that name, so we better handle that case最好不要为此使用任何动态类型,并让您的类实现一个接口。
然后,您可以在运行时检查对象是否实现该接口,从而具有预期的方法(或属性)。
我认为这是唯一正确的方法。
您所指的是鸭子类型,这在您已经知道该对象具有该方法但编译器无法检查该方法的情况下非常有用。
例如,这在 COM 互操作场景中很有用。 (查看这篇文章)
例如,如果您想将鸭子类型与反射结合起来,那么我认为您是错过了鸭子打字的目标。
Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface.
Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).
I think this is the only correct way.
The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that.
This is useful in COM interop scenarios for instance. (check this article)
If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.
为了避免 AmbigeousMatchException,我宁愿说
To avoid
AmbiguousMatchException
, I would rather say