0

I'm trying to get current submission instance in csharp csx script. I need to invoke script method with reflection:

using System.Reflection;

void Foo()
{

}

var foo = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("Foo");
foo.Invoke(???, null);

I cannot use this keyword, as it's not available in scripting context:

error CS0027: Keyword `this` is not available in the current context

Trying to invoke foo.Invoke(null, null) fails because Foo is not a static method.

Does anyone know if this is possible?

ghord
  • 13,260
  • 6
  • 44
  • 69
  • Don't think it is possible ('this' refer to an instance of a class which is not the case here). What are you trying to do? Anyway - if you wrap it all in a class it would work. – idanp Jan 23 '18 at 07:41

1 Answers1

0

While it's not the most elegant solution, it's possible to get instance using expression trees.

Anywhere in your script place following code:

using System.Reflection;
using System.Linq.Expressions;

void Stub() { }

object GetInstance(Expression<Action> expr)
{
    var invoke = (MethodCallExpression)expr.Body;
    return ((ConstantExpression)invoke.Object).Value;
}

var This = GetInstance(() => Stub());

Now the This variable contains current instance of Submission, and one can safely call foo.Invoke(This, null)

ghord
  • 13,260
  • 6
  • 44
  • 69