Adding methods to ExpandoObjects
UPDATE
The problem is not the code, the problem is that you apparently can't evaluate dynamic objects from the immediate window.
I'm trying to tack on methods to an ExpandoObject but not sure how to get it to work. Here's my code:dynamic myObj = new ExpandoObject();
myObj.First = "Micah";
myObj.Last = "Martin";开发者_如何转开发
myObj.AsString = new Func<string>(() => myObj.First + " " + myObj.Last);
//No matter what I do I get 'object' does not contain a definition for 'AsString'
myObj.AsString;
myObj.AsString();
myObj.AsString.Invoke();
Anyone know how to do this?
Are you sure you included all the code?
I just tested and ran the following and was successful:
dynamic obj = new ExpandoObject();
obj.First = "Hello";
obj.Last = "World!";
obj.AsString = new Func<string>(() => obj.First + " " + obj.Last);
// Displays "Hello World!"
Console.WriteLine(obj.AsString());
The compiler will complain about
myObj.AsString; // only assignment, call, increment, decrement, and new object expressions can be used as a statement
So get rid of it. And of course get rid of the line of code that you say does not compile. However, the rest of your code should work once those bits are fixed. Example (plus adding another "method"):
dynamic myObj = new ExpandoObject();
myObj.First = "Stack";
myObj.Last = "Overflow";
Action<int> PrintInt = input => Console.WriteLine(input.ToString());
myObj.PrintInt = PrintInt;
myObj.PrintInt(1);
myObj.AsString = new Func<string>(() => myObj.First + " " + myObj.Last);
string s = myObj.AsString();
Console.WriteLine(s);
精彩评论