簡體   English   中英

I have class A, which contains class B, I want to use class A in class B without instantiating class A

[英]I have class A, which contains class B, I want to use class A in class B without instantiating class A

希望標題相當清楚,但這里有更多細節:

Class A 包含一個 ChromeDriver 變量和對其進行操作的方法。 我在 class A 中定義了 class B 代表一個菜單,我需要訪問 class A 在 ZA2F2ED4F8EBC2C61DZC20 中的一些方法。

提出問題的另一種方法:如何在不創建 Class A 的另一個實例的情況下從 Class B(內部類)訪問 Class A(外部類)?

我對 C# 還是很陌生,到目前為止還沒有找到方法來做到這一點,到目前為止我的研究只是出現了死胡同。 可能嗎? 如果沒有,為什么不呢?

感謝您在正確方向上的任何答案和指示!

- 更新 -

抱歉耽擱了這么久,這里是需要上述情況的情況:

 public sealed class CatalogPane
 {

    protected CatalogPane(Application application, string automationId, int index)
    {
        Pane = application.MainWindow.FindElementByClassName("CatalogMenu")
            .Where(item => item.AutomationId().StartsWith(automationId))
            .ElementAtOrDefault(index);
    }

    public AppiumWebElement Pane { get; set; }

    public static class contextMenu
    {       

        public static void Select(MenuOption option) // MenuOption has property id that holds an automationId
        {
            Pane.FindElementByAccessibilityId(option.id).Click(); // I do not have access to Pane so this is not possible. I would like to be able to do this.
        }

    }
 }

抱歉-這確實應該是評論,但我沒有足夠的聲譽點來評論...如果您需要在內部 class 中使用外部 class 的方法,聽起來您的分工是錯誤的(您的對象應該做他們需要做的事情)。 但是沒有看到任何代碼,我們無法知道您的實際目標是什么。 也許它應該是class B的方法,如果你在class A中需要它那么使用B的實例?

The good approach would be to make it possible that you can give class B a reference to your class A for example give class B a second (or do it in the first) constructor where you pass the instance of A. Maybe when class A is實例化:

Class A {
    Class A() {
        this.b = new B(this);
    }
/// Rest of A
}

據我了解,這將是您需要的示例。

public class A 
{
    public B ClassB { get; private set; }

    public A()
    {
        ClassB = new B(this); //pass the parent class as a parameter
    }

    public class B
    {
        private A ClassA { get; set; } //With this property you can access the values of class A

        public B(A _classA)
        {
            ClassA = _classA;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM