使用带有 this 关键字的 ref 参数?
有没有办法强制 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();
}
Is there a way to force the this keyword to act as a ref argument? I would like to pass in a visitor that modifies multiple properties on the object, but this only wants to act like a value parameter.
Code in Object:
public void Accept(Visitor<MyObject> visitor)
{
visitor.Visit(this);
}
Code in Visitor:
public void Visit(ref Visitor<MyObject> receiver)
{
receiver.Property = new PropertyValue();
receiver.Property2 = new PropertyValue();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
由于您实际上并未更改
receiver
所指的内容,因此不需要ref
关键字。但是,如果是这种情况,您将无法使this
引用另一个实例。为了将
this
作为ref
参数传递,您需要这样编写:该代码将无法编译:"Cannot pass '; '作为 ref 或 out 参数,因为它是只读的”
Since you are not actually changing what
receiver
refers to there is no need for theref
keyword. However, if that would have been the case, you would not be able to makethis
refer to another instance.In order to pass
this
as aref
parameter, you would need to write it like this:That code will not compile: "Cannot pass '<this>' as a ref or out argument because it is read-only"
如果您的
Visitor
是一个类,那么您不需要ref
关键字。如果在方法中更改,类中的所有信息都会自动更改
If your
Visitor<T>
is a class, then you don't need theref
keyword.All the info inside a class is automatically changed if they are changed in a method
听起来您已经得到了更大问题的答案。但无论如何,让我们考虑一下这个问题。
是的。逻辑地完成它。
事实上,这就是“this”在幕后以值类型实现的方式。当你有一个(最糟糕的做法!实际上不要这样做)可变值类型时:
既然 S 的实例是按值传递的,那么 M 是如何改变 s 的呢? s 必须通过引用传递!事实上,我们生成的代码就像您编写的代码一样:
简而言之,结构中的“this”已经作为 ref 参数传递,因此再次传递它是没有问题的。这样做几乎总是一个糟糕的想法,但它是合法的。
It sounds like you got an answer to your larger question already. But let's consider this one anyway.
Yes. Work it through logically.
And in fact that is how "this" is implemented in a value type behind the scenes. When you have a (worst practice! do not actually do this) mutable value type:
Since instances of S are passed by value how is it that M mutates s? s must be passed by reference! In fact the code we generate is just as if you'd written something like:
In short, a "this" in a struct already is passed as a ref parameter, so there is no problem passing it along again. Doing so is almost always a terrible idea but it is legal.
您真的需要 ref 关键字吗?
如果您更改接收器实例, ref 会很有用
例如
接收者=空;
否则,
receiver.Property 也可以在没有 ref 关键字的情况下访问
Do you really need the ref keyword ?
ref would be useful if you change receiver instance
e.g.
receiver = null;
otherwise
receiver.Property is accessible also without ref keyword