c# - 将 ref 参数与 this 关键字一起使用?

标签 c# ref this-pointer

有没有办法强制 this 关键字充当 ref 参数?我想传递一个修改对象多个属性的访问者,但这只想充当值参数。

对象中的代码:

public void Accept(Visitor<MyObject> visitor)
{
    visitor.Visit(this);
}

访问者中的代码:

public void Visit(ref Visitor<MyObject> receiver)
{
    receiver.Property = new PropertyValue();
    receiver.Property2 = new PropertyValue();
}

最佳答案

因为您实际上并没有更改receiver 所指的内容,所以不需要ref 关键字。但是,如果是这种情况,您将无法使 this 引用另一个实例。

为了将 this 作为 ref 参数传递,您需要这样写:

Visit(ref this);

该代码将无法编译:“无法将‘’作为 ref 或 out 参数传递,因为它是只读的”

关于c# - 将 ref 参数与 this 关键字一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2647030/

相关文章:

c# - P/Invoke 是否执行 DLL 然后将其关闭?

c# - 找不到类型或命名空间名称 'Neodynamic'(是否缺少 using 指令或程序集引用?)

javascript - Jquery - 无法使用 $(this) 定位正确的元素

c++ - 下面的 C++ 代码中是否需要使用 'new' 运算符?

c# - 错误消息 : A fatal error occurred while creating a TLS client credential. 内部错误状态为 10013

c# - newtonsoft.json 与 microsoft.aspnetcore.mvc.newtonsoft.json - 有什么区别?

c# - 在这种情况下哪个更好,return 或 ref

arrays - Perl 数组引用和避免 "Type of arg 1 to keys must be hash"错误

html - 为任何类型的 HTML 元素键入自定义 useRef Hook

c++ - 引用此指针并从类的构造函数内部连接一个lambda是否合法?