问题
Is there any way to call method by name and specify arguments without using dynamic? (C#)
UPDATE:
` public class Program { public static void Main(string[] args) { ScriptEngine engine = Python.CreateEngine(); ScriptScope scope = engine.CreateScope();
engine.ExecuteFile("script.py", scope);
dynamic calculator = scope.GetVariable("Calculator");
dynamic calculatorInstance = engine.Operations.CreateInstance(calculator);
dynamic result = engine.Operations.InvokeMember(calculatorInstance, "sample");
Console.ReadKey();
}
}
`
class Calculator:
def sample(self):
return 'test'
That works great
回答1:
You can use the ObjectOperations
class to perform dynamic operations, and you can get an instance of it from a ScriptEngine
instance:
ScriptEngine engine = ...;
object result = engine.Operations.InvokeMember(o, "foo", 1, 2, "3");
回答2:
Open Source Impromptu-Interface (can be found in nuget) has a bunch of methods for doing reflection-like invocation on any dynamic object, python, ruby, c#, etc, as it uses the dlr c# binder code.
Impromptu.InvokeMember(o, "foo", 1, 2, "3")
But in this case, JeffHardy's answer is best, since you are already working with a script engine.
来源:https://stackoverflow.com/questions/8970458/ironpython-call-method-by-name