1

したがって、2つの関数があり、興味深い問題が発生しています。基本的に、簡単にインクルードできる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)'
4

2 に答える 2

2

クラスのインスタンスが必要です。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"));
}
于 2012-05-08T19:11:58.893 に答える
0

basicFunctions.phpPort.includerを静的メソッドとして呼び出す場合は、次のようにstaticキーワードが必要です。

public static void returnError
public static string includer

静的呼び出しを行っていない場合、ベースページは「this」から呼び出す必要があります

if ('stuff happens') {
    this.returnError();
}
于 2012-05-08T19:12:40.253 に答える