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;
int x = foo.Bar;
foo.Baz = (Func<int, int, int>)
delegate(int x, int y)
{
return x + y;
};
foo.Baz(1, 2);
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; };
});