c# - 从委托(delegate)访问范围变量

标签 c# delegates

这听起来很奇怪,但是是否可以从委托(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/

相关文章:

c# - WPF TabControl上下文菜单在mvvm中右键单击项目

iOS Swift : Closures (Callbacks) versus Delegates, 什么时候使用哪个?

ios - 哪个更好 - 依赖委托(delegate)还是通过对象持久化 - iOS

ios - 委托(delegate)设置不正确

c# - 未找到标记扩展

c# - 如何使用 CultureInfo 获取 12 小时或 24 小时时间(不带日期)

c# - 如何在 C# 的 ListView 中添加图像?

c# - 原始泛型类型列表 C#

ios - 在 Swift iOS 中为协议(protocol)分配委托(delegate)时出现编译器错误

c# - 检查 C# Action/Lambda/Delegate 是否包含任何代码/语句