Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 获取当前类实例_C#_Class_Instance - Fatal编程技术网

C# 获取当前类实例

C# 获取当前类实例,c#,class,instance,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 exampl

如何获取类的当前实例

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

代码示例:

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();
}
我只想在btnSearch.Text==“Search”时创建实例;当btnSearch.Text==“取消”时;我想调用srch.Cancel()

////
由于nmclean,问题解决了,我必须在更高的范围内声明搜索类才能访问当前运行的实例。

您的
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();
        }
    }
}

“上面的例子”是什么意思?
Searcher
的实例?是否要从上述范围调用
srch
的方法?请定义“类的当前实例”。。你是说一个单例,或者服务定位器,或者…?没有“当前实例”这样的东西。如果有多个实例呢?如果有多个线程呢?我也不会依赖按钮的文本。相反,保持一个“搜索进行中”的标志。您还可以按照下面的建议提高
srch
的范围,并使用
srch!=null
作为您的“搜索进行中”标志。经过大量调试和试用,这就像一个魅力。非常感谢,如果有任何混乱,很抱歉。