这听起来很奇怪,但是是否可以从委托(delegate)实现中访问类实例的属性?我想让类用户能够向类中注入(inject)更多代码和功能(在运行时执行)。如果无法使用以下方法,我还有其他选择吗?
测试.cs:
Class Test{
public int P {get; set;};
public Action A;
public void Run(){
this.A();
}
}
主要内容:
t = new Test();
t.A = () => { /* Modify t.P in here. */};
t.Run();
最佳答案
在 C# 中,this
关键字绑定(bind)到词法作用域,因此它将始终引用分配了 Action
的类实例。
为了克服这个问题,您可以简单地将 Test
实例作为参数传递给 Action
,如下所示:
public class Test
{
public int P { get; set; }
public Action<Test> A;
public void Run()
{
this.A(this);
}
}
用法:
var t = new Test();
t.A = test =>
{
// you can now access `Test` properties
var p = test.P;
};
t.Run();
或者,您可以使用闭包“捕获”您当前对 t
的引用,但这通常需要编译器生成一个类型来表示该委托(delegate)(这可能有性能问题,具体取决于你的场景):
var t = new Test();
t.A = () => {
// access Test properties using `t`
var p = t.P;
};
t.Run();
关于c# - 从委托(delegate)访问范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52042628/