如何使用“ref”作为全球变量 [英] how to use "ref" as global variable

查看:80
本文介绍了如何使用“ref”作为全球变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

i在form1中有一个数组,我把它作为ref发送到form2构造函数

in form2我想把数组作为全局来使用它各种方法



form1电话

Hello
i have an array in form1 and i send it as ref to form2 constructor
in form2 i want to make the array as "global" to use it in various methods

form1 call

Form2 form = new ImageView(ref array1);
            form.ShowDialog();





form2构造函数



form2 constructor

public Form2(ref string[] arr)
        {
            InitializeComponent();
            
        }









或给我可以用另一种方式。





or give me another way can i use.

推荐答案

你好,



看看这里:

是否可以定义Windows窗体中的全局变量? [ ^ ]


如果只想在form2中使用数组,请将它从form1传递给2然后再将它存储在类级变量中。
If you want to make your array used across form2 only, pass it from form1 to 2 and then store it in a class level variable.


注意,数组是引用类型。没有必要通过引用传递它。只有当您想要通过某些此类函数替换数组对象时,此类双引用才有用。如果你想改变数组长度,确实需要它,因为数组在这方面是不可变的(但强烈建议使用一些集合而不是数组)。



总的来说,通过引用传递数组实际上是没用的。如果函数只修改了一些元素,则不需要ref,如果要更改长度,则不应使用数组。最后,如果你想用某些函数替换整个数组,那么就无法触及全局(更准确地说,是外部范围的数组)。只有调用方法才会收到被替换的对象。



更重要的是:模仿全局对象的想法(真正的全局对象在.NET中不可用,因为一些非常好的理由)真的非常糟糕。如果你正确地分析了你的代码设计,你可能会得出结论,这是永远不需要的,但可能是灾难性的。只是不要这样做。如果你可以解释你的最终目标,也许我可以建议做什么。



-SA
Note that array is a reference type. There is no a need to pass it by reference. Such double reference would only be useful if you want to replace the array object by some of such functions. It can really be needed if you want to change the array length, as an array is immutable in this respect (but then it would be strongly recommended to use some collection instead of array).

Overall, passing an array by reference is practically quite useless. If the functions just modify some elements, you don't need "ref", and if you want to change the length, array should not be used. Finally, if you want to replace the whole array by some functions by whatever reason, it could not touch the "global" (more exactly, outer-scope array). Only the calling method would receive the replaced object.

Even more importantly: the idea to mimic "global" objects (real global objects are not available in .NET, for some very good reasons) is really, really bad. If you properly analyze your code design, you may come to conclusion that this is never needed but can be disastrous. Just don't do it. If you could explain the your ultimate goals, perhaps I would be able to suggest what to do instead.

—SA


这篇关于如何使用“ref”作为全球变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆