C# 中的引用传递到底是如何工作的?
我想知道 C# 中的引用传递是如何工作的。如果我通过引用函数传递 WPF DataGrid 控件,并慢慢让该函数将项目添加到其 DataGrid.Items 集合中,则 UI 中的 DataGrid 是否会随着每个新的 DataGrid.Items.Add() 调用而更新?或者它只会在函数返回时更新?我想实现前一种情况,所以如果通过引用传递不能解决问题,我希望得到一些关于如何实现这一点的建议。提前致谢。
I am wondering how passing by reference works in C#. If I pass a WPF DataGrid control by reference to a function, and slowly have the function add items to its DataGrid.Items collection, will the DataGrid in the UI update with each new DataGrid.Items.Add() call? Or will it only update when the function returns? I would like to achieve the former scenario, so if passing by reference doesn't do the trick, I would love some advice on how to accomplish this. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您想要前一种情况,请在使用 Add() 方法后在下一条语句中调用 datagrid 的 UpdateLayout() 函数。希望这会有所帮助。
if u want the former scenario, then call the function UpdateLayout() of datagrid in the next statement after you use Add() method. Hope this will help.
无论如何,通过引用传递与您的情况无关。通过引用传递(即
ref
)允许您分配给调用范围中的变量。你并不想这么做。您只想访问DataGrid
引用并访问其Items
字段。这根本不需要ref
。Passing by reference is irrelevant to your situation anyway. Passing by reference (i.e.
ref
) allows you to assign to the variable in the calling scope. You are not trying to do that. You only want to access theDataGrid
reference and access itsItems
field. That does not requireref
at all.就像 Ethicallogics 所说的扩展一样,我将子类化并重写 add ,以便它每次都调用 UpdateLayout ,那么您就不必担心它。
一般来说,最好对您需要的所有 .net 类(特别是与 UI 相关的任何内容)进行子类化,这样,如果您遇到自定义需求,则以后就不必再这样做了。始终使用您自己的子类。
Just as an extension to what Ethicallogics said I would subclass and override add so that it calls UpdateLayout each time, then you don't have to worry about it.
In general it's good to subclass all the .net classes [specifically for anything UI related] you will need, that way if you run into custom requirements you don't have to do it later. Use your own subclasses at all times.