【问题标题】:Object reference is required for the nonstatic field method or property非静态字段方法或属性需要对象引用
【发布时间】:2017-01-12 19:11:53
【问题描述】:

我正在使用带有 WebMethod 的 C# aspx Web 表单,但在尝试使用公共方法调用类时遇到问题,我收到以下错误消息:

非静态字段方法或属性需要对象引用。

这是我的代码示例。

DB_Class

public int Cuenta(User us, int opcion)
{
    string sql = "";
    int res = 0;

    switch (opcion)
    {
        //Insert
        case 1:
            sql = "query...";
            break;
            //Update
        case 2:
            sql = "";
            break;
            //Delete
        case 3:
            sql = "";
            break;
    }
    //More code, using executenonquery etc. there is no problem with that.
    return res;
}

ASPX、Web 方法代码

db_Class conn = new db_Class();

[WebMethod]
public static string RegistrarCuenta(int id, string usuario, string nombre, string apellido, string email, string password, string fechaNacimiento, int tipo, int op)
{
    string respuesta = "Ha Ocurrido Un error.";

    try
    {
        User us = new User(id, usuario, nombre, apellido, email, password, fechaNacimiento, tipo);
        //I get the error here.
        int resp = conn.Cuenta(us, op);

        if (resp > 0)
            respuesta = "Operacion Realizada Correctamente.";
    }
    catch (Exception ex)
    {
        respuesta = "Ha Ocurrido un error: " + ex.Message;
    }

    return respuesta;
}

我在这里寻找解决方案,但我没有发现任何类似我的问题(试图调用另一个类中的方法)。此外,我尝试将我的 webmethod 更改为公共字符串而不是公共静态字符串,但是现在我得到了这个浏览器错误:未知的 web 方法,我不知道这个问题是否是因为我的 ajax 代码中的错误 url 引用,这是我的 ajax 代码:

 $.ajax({
            type: 'POST',
            url: 'registrar.aspx/RegistrarCuenta',
            data: '{' +
                '"id":' + id +
                ',"usuario":"' + user +
                '","nombre":"' + nombre +
                '","apellido":"' + apellido +
                '","email":"' + email +
                '","password":"' + password +
                '","fechaNacimiento":"' + date +
                '","tipo":' + 2 +
                ',"op":' + 1 + '}',
            dataType: "json",               // Tipo de datos que se envian
            contentType: "application/json",            // Tipo de datos qu se envian
            timeout: 60000,             // Tiempo de espera para que occura un error de timeout
            error: function (xhr) {     // Evento que se dispara al ocurrir un error en la peticion
                swal("Algo a salido mal...", "Error!", "error")
            },
            success: function (data) {   // Evento que se dispara cuando se realiza correctamente
                swal(data.d, "", "success");
            }
        });

PD。 registrar.aspx 位于我的根文件夹中,不在根文件夹中的子文件夹等。

如何解决我的问题?或者我可以改变什么来使它工作。

【问题讨论】:

    标签: c# asp.net webmethod


    【解决方案1】:

    conn 是实例成员,无法在静态上下文中访问它,因为没有可使用的实例。

    更重要的是,使用共享连接对象(尤其是在静态上下文中)通常是一个非常糟糕的主意。只需在需要的地方/时间创建连接对象:

    db_Class conn = new db_Class();
    int resp = conn.Cuenta(us, op);
    

    您可以(并且可能应该)删除类级别的conn 成员并保持连接范围非常小。如果它实现了IDisposable,你也应该利用它:

    int resp = 0;
    using (db_Class conn = new db_Class())
    {
        resp = conn.Cuenta(us, op);
    }
    

    【讨论】:

    • 非常感谢!
    【解决方案2】:

    在 C# 或 Java 中,

    您不能在静态方法中访问非静态成员(变量或函数)。您可以按照@David 的建议将它们声明为静态或在 Web 方法中初始化局部变量。

    也检查这个链接 https://msdn.microsoft.com/en-us/library/98f28cdx.aspx

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多