我正在开发一个 CSharp 表达式评估器,如下所示。该组件生成代码并在内存中编译,然后加载生成的程序集,创建生成的类的实例并运行它。结果保存在字典中。
我的问题是一切正常,直到最后一行代码失败,但有异常:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException 'object' 不包含 'FirstName' 的定义。
但是,Visual Studio 能够向我展示专业的变量内容:
Professional = { FirstName = Juan Pablo,
LastName = Ibañez,
Certifications = <>f__AnonymousType0`3[System.String,System.String,System.String][],
SayHi = System.Action }
这是代码:
static void Main(string[] args)
{
const string data = @"results[""professional""] =
new
{
FirstName = ""Juan Pablo"",
LastName = ""Ibañez"",
Certifications = new[]
{
new { Provider=""MSFT"", ExamCode = ""70-536"", Title = ""TS: Microsoft .NET Framework – Application Development Foundation"" },
new { Provider=""MSFT"", ExamCode = ""70-505"", Title = ""TS: Microsoft .NET Framework – Application Development Foundation"" },
new { Provider=""MSFT"", ExamCode = ""70-563"", Title = ""TS: Microsoft .NET Framework – Application Development Foundation"" }
},
SayHi = new System.Action(()=> System.Console.WriteLine(""Hi""))
};";
var eval = CSharpEvaluator.Evaluate(data); // return a disctionary<string, object>
dynamic professional = eval["professional"];
Console.WriteLine("First Name: {0}", professional.FirstName);
有任何想法吗?
谢谢你。