向ExpandoObjects添加方法

时间:2010-09-16 14:15:12

标签: c# dynamic .net-4.0 expandoobject

更新

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


我正试图解决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();

任何人都知道怎么做?

2 个答案:

答案 0 :(得分: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());

答案 1 :(得分: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);