How do you implement C#4's IDynamicObject interface?

后端 未结 5 996
忘掉有多难
忘掉有多难 2021-01-01 00:03

To implement \"method-missing\"-semantics and such in C# 4.0, you have to implement IDynamicObject:

public interface IDynamicObject
{
  MetaObject GetMetaObj         


        
相关标签:
5条回答
  • 2021-01-01 00:51

    Here is what I have figured out so far:

    The Dynamic Language Runtime is currently maintained as part of the IronPython project. So that is the best place to go for information.

    The easiest way to implement a class supporting IDynamicObject seems to be to derive from Microsoft.Scripting.Actions.Dynamic and override the relevant methods, for instance the Call-method to implement function call semantics. It looks like Microsoft.Scripting.Actions.Dynamic hasn't been included in the CTP, but the one from IronPython 2.0 looks like it will work.

    I am still unclear on the exact meaning of the "parameter"-parameter, but it seems to provide context for the binding of the dynamic-object.

    0 讨论(0)
  • 2021-01-01 00:53

    This presentation also provides a lot of information about the DLR:

    • Deep Dive: Dynamic Languages in Microsoft .NET by Jim Hugunin.
    0 讨论(0)
  • 2021-01-01 00:57

    The short answer is that the MetaObject is what's responsible for actually generating the code that will be run at the call site. The mechanism that it uses for this is LINQ expression trees, which have been enhanced in the DLR. So instead of starting with an object, it starts with an expression that represents the object, and ultimately it's going to need to return an expression tree that describes the action to be taken.

    When playing with this, please remember that the version of System.Core in the CTP was taken from a snapshot at the end of August. It doesn't correspond very cleanly to any particular beta of IronPython. A number of changes have been made to the DLR since then.

    Also, for compatibility with the CLR v2 System.Core, releases of IronPython starting with either beta 4 or beta 5 now rename everything in that's in the System namespace to be in the Microsoft namespace instead.

    0 讨论(0)
  • 2021-01-01 00:59

    If you want an end to end sample including source code, resulting in a dynamic object that stores value for arbitrary properties in a Dictionary then my post "A first look at Duck Typing in C# 4.0" could be right for you. I wrote that post to show how dynamic object can be cast to statically typed interfaces. It has a complete working implementation of a Duck that is a IDynamicObject and may acts like a IQuack.

    If you need more information contact me on my blog and I will help you along, as good as I can.

    0 讨论(0)
  • 2021-01-01 01:03

    I just blogged about how to do this here:

    http://mikehadlow.blogspot.com/2008/10/dynamic-dispatch-in-c-40.html

    0 讨论(0)
提交回复
热议问题