繁体   English   中英

MS Visual Studio C#-有人可以向我解释为什么我的代码不起作用以及如何使它起作用吗?

[英]MS Visual Studio C# - Can someone explain to me why my code isn't working and how I can get it to work?

我正在编写一个程序,以便在Windows Active Directory中进行搜索,并将搜索结果返回到列表框中的另一个表单。

这是我的getter方法在主窗体上的样子:

public List<String> getSearchResults()
{
    List<String> accountList = new List<String>();
    foreach (SearchResult account in searchResultCollection)
    {
        accountList.Add(account.Properties["cn"][0].ToString());
    }
    return accountList;
}

在加载时仅在第二种形式上调用它:

private void AccSelect_Form_Load(object sender, EventArgs e)
{
    List<String> accountList = Main_Form.getSearchResults();
}

但是,编译器告诉我“非静态方法需要对象引用”。 但是我的getter方法根本不能是静态的。

在问这个问题之前,从我的研究看来,我需要拥有我的getter方法(因此是我的主要形式)的类的实例才能运行。 很好,因为我的第一种形式是实例化第二种形式的。 反之,如果没有第一个表单,第二个表单将永远不会运行。

谁能给我一个可能的解决方案? :C

当您需要从子窗体中调用主窗体中的方法时,可以这样编写代码(假设您的主窗体为MainForm类型):

MainForm parent = (MainForm)this.Owner;
parent.getSearchResult();//CustomMethodName();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM