CSX 获取当前提交实例
CSX getting current submission instance
我正在尝试在 csharp csx 脚本中获取当前提交实例。我需要用反射调用脚本方法:
using System.Reflection;
void Foo()
{
}
var foo = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("Foo");
foo.Invoke(???, null);
我不能使用 this
关键字,因为它在脚本上下文中不可用:
error CS0027: Keyword `this` is not available in the current context
尝试调用 foo.Invoke(null, null)
失败,因为 Foo
不是静态方法。
有人知道这是否可行吗?
虽然这不是最优雅的解决方案,但可以使用表达式树获取实例。
在脚本的任意位置放置以下代码:
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());
现在 This
变量包含提交的当前实例,可以安全地调用 foo.Invoke(This, null)
我正在尝试在 csharp csx 脚本中获取当前提交实例。我需要用反射调用脚本方法:
using System.Reflection;
void Foo()
{
}
var foo = MethodBase.GetCurrentMethod().DeclaringType.GetMethod("Foo");
foo.Invoke(???, null);
我不能使用 this
关键字,因为它在脚本上下文中不可用:
error CS0027: Keyword `this` is not available in the current context
尝试调用 foo.Invoke(null, null)
失败,因为 Foo
不是静态方法。
有人知道这是否可行吗?
虽然这不是最优雅的解决方案,但可以使用表达式树获取实例。
在脚本的任意位置放置以下代码:
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());
现在 This
变量包含提交的当前实例,可以安全地调用 foo.Invoke(This, null)