如何通过裁判在C#中通过这个?裁判

2023-09-03 02:45:33 作者:再爱也不易

在我的类(ClassA的)我想创建另一个类(ClassB的)为它提供一个参考谁发起了它的创建对象的相关实例。所以,我提供了ClassB的有construcror服用(REF ClassB的主站)的说法。但在ClassA的,我不能只是叫无功奴=新的ClassB的(参考本)。如何实现这一点?

In a class (ClassA) of mine I want to create a related instance of another class (ClassB) providing it with a reference to the object who has initiated it's creation. So I've provided ClassB with a construcror taking a (ref ClassB master) argument. But in ClassA I can't just call var slave = new ClassB(ref this). How to implement this?

推荐答案

REF 关键字原因的按引用传递语义 - 也就是说,如果变量的重新分配中调用的函数,它会重新分配的的变量的调用方和

The ref keyword causes Pass by Reference semantics - that is, if the variable is re-assigned in the called function, it will re-assign the variable in the caller as well.

显然,这仅适用于如果一个的可变的 2 (可重新assigne到)被直接作为参数传递的,如果一个任意的前$不会工作p $ pssion传递。在这种情况下,不是一个变量,而一个特别恩pression不能被重新分配的,所以不能使用。

Obviously, this only works if a variable2 (which can be re-assigne to) is directly passed as the argument and will not work if an arbitrary expression is passed. In this case, this is not a variable, rather a special expression which cannot be re-assigned, and so cannot be used.

因此​​,这会工作:(但请看其他答案,继续读,为什么这很可能的不需要的和/或只是愚蠢)

As such, this would work: (But please see other answers and keep reading as to why this is likely not required and/or just silly.)

var me = this;
var slave = new ClassB(ref me);

然而, REF erence的不应该与的的擦肩而过对象[分享] 1 语义。通过对象传递意味着如果一个对象传递,是的对象传递:对象是的没有的复制/复制/复制。 如果的对象的突变则的对象的突变。所有的 有路过的C#语义对象引用类型,除非任何 REF 退出被使用。 (该关键字声明一个新的引用类型,如在后的情况下)。

However, Pass by reference should not be confused with Pass by Object [Sharing]1 semantics. Pass by Object means that if an object is passed, that object is passed: the object is not copied/cloned/duplicated. If the object is mutated then the object is mutated. All Reference Types have Pass by Object semantics in C# unless either ref or out are used. (The class keyword declares a new reference type, as in the case in the post).

在另一方面,值类型(如结构),其中 INT 的Guid KeyValuePair< K,V&GT ; ,有按值传递语义 - 在这种情况下副本的是的制作,因此,如果该值被修改,只值结构(这是一个副本)的变化

On the other hand, Value Types (e.g. struct), including int and Guid and KeyValuePair<K,V>, have Pass by Value semantics - in this case a copy is made and thus, if the value is modified, only the value struct (which is a copy) changes.

快乐编码

1 下方的C#/。NET实现路过对象通过传递的的对象引用的按价值。然而,上述规则正确地描述观察到的语义和效果。

1 Underneath C#/.NET achieves Pass by Object by passing a reference to an object by Value. However, the rules above correctly describe the observable semantics and effects.

2 与C#中,只允许变量与 REF 使用VB.NET允许使用属性。 VB.NET的编译器会自动创建一个临时变量和内隐读/编译期间写入属性的指令。

2 Unlike C#, which only allows variables to be used with ref, VB.NET allows Properties to be used. The VB.NET compiler automatically creates a temporary variable and implicit reading/writing instructions of the property during compilation.