C # 4.0, Ways on the fly?

With the introduction of things like duck printing, I would love it if I were to compose object methods on the fly, in addition to extension methods. Does anyone know if this is possible? I know that MS is worried about creating a wireframe on the fly, but they seem to dip their toes into the water.

Update: thanks to Paul for clarification. For example, let's say I am returning a new dynamic object from LINQ and would like to add some methods to it on the fly.

+5
source share
3 answers

In light of the updated answer, you are not really looking for “dynamic methods” as well as “dynamic objects” so that you can add new properties and methods to them at runtime. If so, then in .NET 4.0 you can use ExpandoObjectin conjunction with dynamic:

dynamic foo = new ExpandoObject();
foo.Bar = 123; // creates a new property on the fly
int x = foo.Bar; // 123

// add a new method (well, a delegate property, but it callable as method)
foo.Baz = (Func<int, int, int>)
    delegate(int x, int y)
    {
        return x + y;
    };

foo.Baz(1, 2); // 3

You can also have “dynamic methods” with expression trees, and as soon as you get a delegate for such a method, you can also create a calling property of the method type from it to ExpandoObject.

For use in LINQ queries, unfortunately, you cannot use object initializers with ExpandoObject; in the simplest case, the following will not compile:

var foo =  new ExpandoObject { Bar = 123; }

, Bar ExpandoObject. , dynamic, , . LINQ :

public static dynamic With(this ExpandoObject o, Action<dynamic> init)
{
     init(o);
     return o;
}

:

from x in xs
select new ExpandoObject().With(o => {
    o.Foo = x;
    o.Bar = (Func<int, int>)delegate(int y) { return x + y; };
});
+11

DynamicMethod / MethodBuilder. , , "", , (DynamicMethod ).

+1

All Articles