调用返回字符串 c# 的方法时出错

本文关键字:方法 出错 返回 字符串 调用 | 更新日期: 2023-09-27 18:36:47

我收到此错误,我不知道为什么。

'非静态字段、方法或 财产'

为什么我需要在这里有一个对象引用?我的代码如下:

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 服务。如何更改此设置以使用对象?

谢谢

调用返回字符串 c# 的方法时出错

由于您的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
    }
}

不能从static方法调用非static方法。

您需要从声明GetChanges()的类实例化一个对象。

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

您的通话只能在您的班级内使用。在课堂外则不然。

您必须将其定义为:

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

并称它

MyClass.GetChanges();

或创建包含 GetChanges 方法的类的实例。

例:

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

然后

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