简体   繁体   English

方法的返回值正在修改作为方法参数传递的对象

[英]Return value of method is modifying an object passed as a method parameter

I'm in a situation where I am writing a method where the return value directly modifies a class which was used to supply paramaters to the method. 我正在编写一种方法,其中返回值直接修改用于向该方法提供参数的类的情况。

Computer.MatchingPassword = PasswordFinder.Find(Computer.Name, PasswordList)

Does assigning to a property of a passed parameter like this have any hazards? 分配给这样传递的参数的属性是否有任何危害?

Technically, your code sample doesn't assign to the parameter, since you passed a property of the Computer object. 从技术上讲,由于传递了Computer对象的属性,因此代码示例分配给参数。

In other words, you only gave the function "name", so assigning to a different property of the same object would have no effect. 换句话说,您给了函数“名称”,因此分配给同一对象的不同属性将无效。

Now, in the more general case, you are still safe. 现在,在更一般的情况下,您仍然很安全。 Even passing the whole object, by the time you assign the return value the method has already completed . 即使传递整个对象,在您分配返回值时, 该方法也已经完成 Any changes you make won't do anything. 您所做的任何更改都不会做任何事情。

In other words, the following code is functionally equivalent: 换句话说,以下代码在功能上是等效的:

string password = PasswordFinder.Find(Computer.Name, PasswordList);
Computer.MatchingPassword = password;

Clearly no problems there. 显然那里没有问题。 This is true even if it was passed by ref , as again, the method is totally done with the object, so any changes to it won't matter. 即使它是由ref传递的,也是如此,同样,该方法完全由对象完成,因此对它的任何更改都将无关紧要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM