6

更新

问题不在于代码,问题在于您显然无法从即时窗口评估动态对象。


我正在尝试将方法附加到 ExpandoObject 但不确定如何使其工作。这是我的代码:

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();

有人知道怎么做吗?

4

2 回答 2

9

你确定你包含了所有的代码?

我刚刚测试并运行了以下内容并成功:

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());
于 2010-09-16T14:25:50.983 回答
0

编译器会抱怨

myObj.AsString; // only assignment, call, increment, decrement, and new object expressions can be used as a statement

所以摆脱它。当然,去掉你说不能编译的那行代码。但是,一旦这些位被修复,您的其余代码应该可以工作。示例(加上添加另一个“方法”):

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);
于 2010-09-16T14:27:30.627 回答