The below code throws a 'MissingMemberException'
ScriptEngine engine = Python.CreateEngine();
ScriptRuntime runtime = engine.Runtime;
ScriptScope scope = runtime.CreateScope();
string code = "emp.Name==\"Bernie\"";
ScriptSource source =
engine.CreateScriptSourceFromString(code, SourceCodeKind.Expression);
var emp = new {Name = "Bernie"};
scope.SetVariable("emp", emp);
var res = (double)source.Execute(scope);
if I declare a type called 'Employee' and give it a member 'Name', and use this instead:
var emp = new Employee {Name = "Bernie"}
It works just as expected. Does anyone know why it doesn't work on anonymous types and is there a workaround?
Your problem is that anonymous types are internal. When the complier generates an anonymous type, it is approximately this:
internal class <>f__AnonymousType0`1'<'<Name>j__TPar'> //or whatever silly name the compiler uses
{
public string Name {get;set;}
}
You can replicate the error you are getting with a concrete class by changing it to be internal:
internal class Employee
{
public string Name { get; set; }
}
OK, so that's why it's happening. How do you fix it? Well, the best approach is to just use a concrete class that is public like you have already found.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With