如何从静态方法调用非静态方法

时间:2012-09-11 12:15:02

标签: c# asp.net static

我需要从static[webmethod]调用非静态方法。它没有接到电话,我使用breakpoints测试它。我试图通过在类中创建一个实例来调用它。 这就是我想要的。

[WebMethod]
public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des)
{
     if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals("")))
     {
        return "null";
     }
     else
     {
        int got_question_id = getting_question_id;
        DataHandler.breg obj = new DataHandler.breg();
        obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des);
        return "inserted";
     }

     querystring object_new = new querystring();
     object_new.show();
  }

querystring是这里的类的名称。控件进入if和else语句取决于输入,但之后它直接跳出。而且当我将鼠标悬停在查询字符串上时,它说

Unreachable code detected.

我该怎么做才能让它发挥作用?

8 个答案:

答案 0 :(得分:2)

那是因为如果前面的return语句你来自两半的if

没有办法让它达到那条线。

答案 1 :(得分:1)

这是因为你在IF和ELSE部分都有一个return语句。

所以不管条件的结果如何;你永远不会低于那个。

答案 2 :(得分:1)

您的方法在if语句之后结束,是否为真(return "null")或不是return "inserted")。所以你的代码在if语句之后(创建查询字符串的地方)永远不会被执行。

答案 3 :(得分:0)

你的问题是你在if和else子句中都退出了你的方法。您的代码基本上是:

MyMethod() 
{
    if (someCondition)
        return
    else
        return

    // Any code at this point cannot be executed, because 
    // you have definitely returned from your method.

}

答案 4 :(得分:0)

querystring object_new = new querystring();
object_new.show();

部分将永远不会到达,因为在你的条件中你的两个块语句都写了一个返回。

答案 5 :(得分:0)

是的,那是因为你在if和else块的末尾都有return语句。

将其更改为

[WebMethod] 
public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des) 
{ 
string ret = "null";
 if (!get_ajax_answer_title.Equals("") || (!get_ajax_answer_title.Equals(""))) 
 { 
    int got_question_id = getting_question_id; 
    DataHandler.breg obj = new DataHandler.breg(); 
    obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des); 
    ret = "inserted"; 
 } 

 querystring object_new = new querystring(); 
 object_new.show(); 

return ret;

}

答案 6 :(得分:0)

Unreachable code detected.是因为if语句的两个路径都提前返回。

    if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals("")))
    {
        return "null"
    }
    else
    {
        return "inserted";
   }
   // Can't get here.

您已正确回答了原始问题,即实例化非静态方法的实例,以便能够在其上调用方法。

querystring object_new = new querystring();
object_new.show();

答案 7 :(得分:0)

  [WebMethod]
public static string get_runtime_values(string get_ajax_answer_title,string get_ajax_answer_des)
    {  string result;
       if (get_ajax_answer_title.Equals("") && (get_ajax_answer_title.Equals("")))
        {
            result="null";
        }
        else
        {
            int got_question_id = getting_question_id;
            DataHandler.breg obj = new DataHandler.breg();
            obj.add_anwers(got_question_id, get_ajax_answer_title, get_ajax_answer_des);
            result="inserted";
       }
        querystring object_new = new querystring();
        object_new.show();
return result;
       }
相关问题