[英]C# language theory question
Given the following method,where I pass configuration byref, then loop through it using a foreach named collection. 给定以下方法,我在其中传递配置byref,然后使用foreach命名集合遍历它。 In the following code sample, will the values that I change in the loop be updated in the main object I passed through by ref, what I mean is NO shallow copies?
在下面的代码示例中,我在循环中更改的值是否会在我通过ref传递的主对象中更新,我的意思是没有浅表副本? Or can you spot any mistake I've made.
或者您能发现我犯的任何错误。
More specifically the line where I call config.Value = ..... the configuration object has a collection of configurations, so will these be updated in the main object (configuration) after this function is called? 更具体地说,在我调用config.Value = .....的行中,配置对象具有配置的集合,那么在调用此函数后,这些配置是否会在主对象(配置)中更新?
Thanks in advance. 提前致谢。
public static void DecryptProviderValues(ref MyConfiguration configuration)
{
foreach (var provider in configuration.Providers)
{
var configItems = provider.Configurations;
foreach (Configuration config in configItems)
{
if(EncryptionManager.IsEncrypted(config.value))
{
config.Value = EncryptionManager.Decrypt(config.Value);
}
}
}
}
Assuming that all the items here are classes (not structs), then yes, but actually there is no need for configuration
to be passed as ref
; 假设这里的所有项目都是类 (不是结构),则可以,但是实际上不需要将
configuration
作为ref
传递; you are already passing a reference (by value), and you aren't re-assigning the reference, so no need for ref
here at all . 您已经传递引用(按价值计算),而你是不是重新分配的参考,所以没有必要
ref
这里的 。 Your changes are preserved and available to the caller. 您的更改将保留并可供调用者使用。
For exactly the same reason that this would work: 出于完全相同的原因,它将起作用:
Configuration x = new Configuration();
Configuration y = x;
x.Value = "abc";
Console.WriteLine(y.Value); // writes "abc"
here, because Configuration
is (presumably) a class
, there is only one object, and two variables that refer to the same object (at a simplified level, they are glorified pointers to the same object). 在这里,由于
Configuration
(大概是一个class
,所以只有一个对象,并且两个变量引用同一对象(在简化级别上,它们是指向同一对象的光荣指针)。
There is no need to pass configuration
by ref
in your case, since in C# you're manipulating references to instances of classes already. 在您的情况下,无需通过
ref
传递configuration
,因为在C#中,您已经在操纵对类实例的引用。
You would use ref
to pass value types like int
or struct
by reference. 您将使用
ref
通过ref
传递诸如int
或struct
的值类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.