Duck type testing with C# 4 for dynamic objects

前端 未结 5 481
遇见更好的自我
遇见更好的自我 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:26

    The shortest path would be to invoke it, and handle the exception if the method does not exist. I come from Python where such method is common in duck-typing, but I don't know if it is widely used in C#4...

    I haven't tested myself since I don't have VC 2010 on my machine

    dynamic Quack(dynamic duck)
    {
        try
        {
            return duck.Quack();
        }
        catch (RuntimeBinderException)
        { return null; }
    }
    

提交回复
热议问题