【问题标题】:C# - An object reference is required for the non-static field, method, or propertyC# - 非静态字段、方法或属性需要对象引用
【发布时间】:2012-05-17 07:21:46
【问题描述】:

所以我有两个函数,我遇到了一个有趣的问题。本质上,我的目标是让我的代码在一个易于包含的 cs 文件中更具可移植性。

这里说的是cs文件:

namespace basicFunctions {
public partial class phpPort : System.Web.UI.Page {
    public string includer(string filename) {
        string path = Server.MapPath("./" + filename);
        string content = System.IO.File.ReadAllText(path);
        return content;
    }
    public void returnError() {
        Response.Write("<h2>An error has occurred!</h2>");
        Response.Write("<p>You have followed an incorrect link. Please double check and try again.</p>");
        Response.Write(includer("footer.html"));
        Response.End();
    }
}
}

这是引用它的页面:

<% @Page Language="C#" Debug="true" Inherits="basicFunctions.phpPort" CodeFile="basicfunctions.cs" %>
<% @Import Namespace="System.Web.Configuration" %>

<script language="C#" runat="server">
void Page_Load(object sender,EventArgs e) {
    Response.Write(basicFunctions.phpPort.includer("header.html"));
    //irrelevant code
    if ('stuff happens') {
        basicFunctions.phpPort.returnError();
    }
    Response.Write(basicFunctions.phpPort.includer("footer.html"));
}
</script>

我得到的错误是上面列出的错误,即:

Compiler Error Message: CS0120: An object reference is required for the non-static field, method, or property 'basicFunctions.phpPort.includer(string)'

【问题讨论】:

    标签: c# asp.net inheritance object include


    【解决方案1】:

    您需要一个 phpPort 类的实例,因为它以及您在其上定义的所有方法都不是静态的。

    由于您位于从该类继承aspx页面上,当它加载它时,它已经该类的一个实例,您可以调用方法直接用。

    您需要修改代码才能直接使用这些功能:

    void Page_Load(object sender,EventArgs e) {
        Response.Write(includer("header.html"));
        //irrelevant code
        if ('stuff happens') {
            returnError();
        }
        Response.Write(includer("footer.html"));
    }
    

    【讨论】:

    • OP 有一个实例-this
    • basicFunction 在这种情况下似乎是命名空间。
    • 这已修复它(我会在允许时将其标记为正确)。现在我在 Server.MapPath 上遇到了An object reference is required for the non-static field, method, or property 'System.Web.UI.Page.Server.get' 的问题。有什么想法吗?
    • @user798080 - 据我所知,这应该可以正常工作(因为您的类继承自 System.Web.UI.Page)。
    • 我为新代码和错误创建了一个新页面 [link]stackoverflow.com/questions/10505187/…。谢谢!
    【解决方案2】:

    如果你想调用 basicFunctions.phpPort.includer 作为静态方法,你需要在其上加上 static 关键字,如下所示:

    public static void returnError
    public static string includer
    

    如果您不进行静态调用,则您的基本页面需要从“this”调用

    if ('stuff happens') {
        this.returnError();
    }
    

    【讨论】:

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