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

后端 未结 4 1331
再見小時候
再見小時候 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:24

    You could write something like that :

    public static bool HasMethod(this object objectToCheck, string methodName)
    {
        var type = objectToCheck.GetType();
        return type.GetMethod(methodName) != null;
    } 
    

    Edit : you can even do an extension method and use it like this

    myObject.HasMethod("SomeMethod");
    

提交回复
热议问题