如何在不使用新的情况下访问类别Froma的另一类 [英] How Do I Access A Class Froma Another Class Without Using New
本文介绍了如何在不使用新的情况下访问类别Froma的另一类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试过MainWindow主;但它没有任何用处,我也不想使用新的..
i tried MainWindow main;. but it wasn't of any use and i dont want to use new for the same..
推荐答案
当你使用new
你创建了一个类的新实例,它的所有字段和属性都独立于任何现有实例:它就像汽车一样。你把你的钱包放在汽车的手套箱里,然后买一辆新车 - 你希望在新车的手套箱里找到你的钱包吗?
所以如果您尝试访问现有的主窗口,则表示您不能使用new
- 您需要获取用户正在查看的窗口的实际实例。 />
如果您是在MainWindow类中执行此操作,那么这很简单 - 您无需执行任何操作,因为您的代码将自动引用当前实例你使用属性或字段名称(除非你在静态方法中,没有实例)。
如果你在课外,那么它很多,更难 - 并且将取决于你的代码如何工作 - 因为你通常不希望代码引用外部窗口,因为这打破了OOP原则。您实际需要实现的是什么?
When you usenew
you create a new instance of the class, which has all it's fields and properties independent to any existing instances: it's like cars. It you put your wallet in the glove box of your car, then buy a new car - would you expect to find your wallet in the new car's glove box?
So you are right not to usenew
if you are trying to access the existing main window - you need to get the actual instance of the window that the user is looking at.
If you are doing this from within the MainWindow class, then that;s pretty easy - you don't have to do anything because your code will automatically reference the current instance when you use a property or field name (unless you are inside a static method, where there is no instance).
If you are outside the class, then it's a lot, lot harder - and will depend on how your code works - because you wouldn't normally want code to refer to external windows as that breaks the OOPs principles. What are you actually trying to achieve that you need this?
这篇关于如何在不使用新的情况下访问类别Froma的另一类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文