2016-03-01 69 views
0

我收到此錯誤,我不知道爲什麼。調用返回字符串c的方法時出錯#

「的對象引用需要非靜態字段,方法或 財產」

爲什麼我要在這裏有一個對象引用?我的代碼如下:

public string GetChanges() 
    { 
     string changelog = ""; 

     MySqlConnection connection = new MySqlConnection("server=127.0.0.1;uid=root;pwd=pass;database=data"); 
     try 
     { 
      connection.Open(); 

      MySqlCommand cmd = new MySqlCommand("SELECT `change_log` FROM version WHERE ID = '1'", connection); 

      MySqlDataReader reader = cmd.ExecuteReader(); 
      while (reader.Read()) 
      { 
       if (!reader.IsDBNull(0)) 
       { 
        changelog = reader.GetString(0); 
       } 
      } 

      connection.Close(); 
     } 
     catch 
     { 
      //MessageBox.Show(e.Message, "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
     } 

     return changelog; 
    } 

我打電話,像這樣上面的函數:

string changelog = GetChanges(); 

爲什麼在這種情況下需要一個對象引用?我無法使用靜態,因爲我正在創建一個不能用靜態方法工作的Web服務。我怎樣才能改變這個使用對象?

感謝

+1

你究竟在哪裏調用'getChanges()'? – Rhumborl

+1

您的'GetChanges'方法是一個實例方法_by default_。您不能在沒有所屬類型名稱的情況下調用它。將它設爲'static'或者調用它的類型如'string changelog = MyType.GetChanges();' –

+0

你在哪裏調用'GetChanges'方法?這聽起來應該將方法的邏輯從Web服務接口分離出來,然後調用邏輯代替代碼中的服務。調用Web服務方法直接聞起來 - 你基本上試圖欺騙接口。 – Luaan

回答

2

由於您的GetChanges不是static方法,它不能被稱爲沒有object的實例,它有一個方法:

public class MyClass { 
    public string GetChanges(){ 
     .... 
     return str; 
    } 
} 

然後,你可以這樣調用:

MyClass insMyClass = new MyClass(); //note the instance of the object MyClass 
string str = insMyClass.GetChanges(); 

或者,如果您聲明爲static,則必須使用類名來調用:

public static string GetChanges(){ //note the static here 
    .... 
    return str; 
} 

這樣稱呼它:

string str = MyClass.GetChanges(); //note the MyClass is the class' name, not the instance of the class 

只有當你在類本身打電話GetChanges,那麼它是好的:

public class MyClass { 
    public string GetChanges(){ 
     .... 
     return str; 
    } 

    public void Foo(){ 
     string somestr = GetChanges(); //this is ok 
    } 
} 
2

您的通話僅是確定你的內類。在外面,不是。

你必須把它定義爲:

public class MyClass{ 
    public static string GetChanges(){...} 
} 

,並調用它

MyClass.GetChanges(); 

或創建一個包含GetChanges方法的類的實例。

實施例:

public class MyClass 
    public string GetChanges(){....} 

然後

var mc = new MyClass(); 
mc.GetChanges(); 
2

不能調用從static方法的非static方法。

您需要從那裏聲明GetChanges()的類實例化一個對象。

Foo f = new Foo(); 
f.GetChanges();