How to check whether an object has certain method/property?

后端 未结 4 1328
再見小時候
再見小時候 2020-11-28 04:08

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.DoStuf

4条回答
  •  野性不改
    2020-11-28 04:17

    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).

    public interface IMyInterface
    {
       void Somemethod();
    }
    
    
    IMyInterface x = anyObject as IMyInterface;
    if( x != null )
    {
       x.Somemethod();
    }
    

    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.

提交回复
热议问题