0

So I have a dynamic object and I want to execute a method from it but I need the method to be passed in as a parameter. I have found no way to do this and was wondering if anyone here could help.

something like:

public static void RunMethod(methodInTheDynamicObject)
{
    myDynamicObject.methodInTheDynamicObject();
}
2
  • 1
    myDynamic as in the dynamic keyword in C# 4 or dynamic as in dynamically compiled? Commented Jan 5, 2012 at 1:47
  • How is it backed? Do you have ability to inquire on its properties in its current form? Commented Jan 5, 2012 at 3:31

3 Answers 3

3

My preference in this case is usually to define a delegate:

public delegate void MyFunction(string p1, int p2);

public void Foo(MyFunction myFunction) {
    myFunction("something", 2);
}

Or you can use System.Reflection and pass in MethodInfo and use it like so:

public void Foo(MethodInfo methodInfo) {
    methodInfo.Invoke(new object[] {"something", 2});
}

You can find out more about MethodInfo.Invoke here. They have some examples. But again, delegates are probably the cleaner way to go.

Sign up to request clarification or add additional context in comments.

Comments

2

I believe you are wanting to pass in a delegate. See the example here: http://geekswithblogs.net/joycsharp/archive/2008/02/15/simple-c-delegate-sample.aspx

If you needed a hardcore approach for runtime generated methods you could try: http://msdn.microsoft.com/en-us/library/exczf7b9.aspx

Comments

0

I probably should have let you know that my dynamic object was an Iron-Python script. Anyways I figured out.

public static void RunMethod(string script, string method, object[] param)
{
    try
    {
        dynamic dynamicObj = Scripts[script];
        var operations = ironPython.Operations;
        operations.InvokeMember(dynamicObj, method, param);
    }
    catch { }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.