Duck type testing with C# 4 for dynamic objects

前端 未结 5 496
遇见更好的自我
遇见更好的自我 2020-12-02 22:57

I\'m wanting to have a simple duck typing example in C# using dynamic objects. It would seem to me, that a dynamic object should have HasValue/HasProperty/HasMethod methods

5条回答
  •  情书的邮戳
    2020-12-02 23:28

    Try this:

        using System.Linq;
        using System.Reflection;
        //...
        public dynamic Quack(dynamic duck, int i)
        {
            Object obj = duck as Object;
    
            if (duck != null)
            {
                //check if object has method Quack()
                MethodInfo method = obj.GetType().GetMethods().
                                FirstOrDefault(x => x.Name == "Quack");
    
                //if yes
                if (method != null)
                {
    
                    //invoke and return value
                    return method.Invoke((object)duck, null);
                }
            }
    
            return null;
        }
    

    Or this (uses only dynamic):

        public static dynamic Quack(dynamic duck)
        {
            try
            {
                //invoke and return value
                return duck.Quack();
            }
            //thrown if method call failed
            catch (RuntimeBinderException)
            {
                return null;
            }        
        }
    

提交回复
热议问题