C#语言理论问题

JL.*_*JL. 1 c#

给定以下方法,我传递配置byref,然后使用foreach命名集合循环它.在下面的代码示例中,我在循环中更改的值是否会在我通过ref传递的主对象中更新,我的意思是NO浅拷贝?或者你能发现我犯过的任何错误.

更具体地说,我调用config.Value = .....的行,配置对象有一组配置,所以在调用这个函数后,它们会在主对象(配置)中更新吗?

提前致谢.

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);

                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

假设所有项目在这里是(非结构),然后是的,但实际上是没有必要configuration将其交给ref; 你已经经过参考(按价值计算),而你是不是重新分配的参考,所以没有必要ref在这里可言.您的更改将保留并可供调用者使用.

出于完全相同的原因,这将起作用:

Configuration x = new Configuration();
Configuration y = x;
x.Value = "abc";
Console.WriteLine(y.Value); // writes "abc"
Run Code Online (Sandbox Code Playgroud)

在这里,因为Configuration(大概)是a class,只有一个对象,两个变量引用同一个对象(在简化的层次上,它们是同一个对象的美化指针).