获取当前的类实例

Net*_*nfo -1 c# class instance

你有没有获得班级的当前实例?

该类有搜索方法和取消方法.

代码示例:

if (btnSearch.Text =="Search")
{
    Searcher srch = new Searcher();
    srch.Search();
    btnSearch.Text = "Cancel";
    return;
}
if (btnSearch.Text == "Cancel")
{
    //call a method in the instance above for example
   srch.Cancel();
}
Run Code Online (Sandbox Code Playgroud)

我想只在btnSearch.Text =="搜索"时创建实例; 当btnSearch.Text =="取消"时; 我想打电话给srch.Cancel();

////感谢nmclean,问题解决了,我觉得必须在更高的范围内声明Search类才能访问当前运行的实例.

nmc*_*ean 7

您的srch变量必须在比函数更高的范围内声明,否则在下次调用函数时它将不会持久存在.这很可能意味着它应该是该类的一个领域:

class YourClass
{
    private Searcher srch;

    void YourMethod()
    {
        if (btnSearch.Text == "Search")
        {
            srch = new Searcher();
            srch.Search();
            btnSearch.Text = "Cancel";
            return;
        }
        if (btnSearch.Text == "Cancel")
        {
            srch.Cancel();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)