Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#-非静态字段、方法或属性需要对象引用_C#_Asp.net_Inheritance_Object_Include - Fatal编程技术网

C#-非静态字段、方法或属性需要对象引用

C#-非静态字段、方法或属性需要对象引用,c#,asp.net,inheritance,object,include,C#,Asp.net,Inheritance,Object,Include,所以我有两个函数,我得到了一个有趣的问题。本质上,我的目标是使我的代码在一个易于包含的cs文件中更具可移植性 下面是所说的cs文件: namespace basicFunctions { public partial class phpPort : System.Web.UI.Page { public string includer(string filename) { string path = Server.MapPath("./" + filename);

所以我有两个函数,我得到了一个有趣的问题。本质上,我的目标是使我的代码在一个易于包含的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();
    }
}
}

您需要一个
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"));
}

如果要将basicFunctions.phpPort.includer作为静态方法调用,则需要使用static关键字,如下所示:

public static void returnError
public static string includer
如果您没有进行静态调用,则需要从“this”调用您的基本页


OP有一个实例-
this
basicFunction在本例中似乎是命名空间。这已经修复了它(如果允许的话,我会将它标记为正确的)。现在我遇到了一个问题:Server.MapPath上的非静态字段、方法或属性'System.Web.UI.Page.Server.get',需要一个对象引用。有什么想法吗?@user798080-据我所知,这应该很有效(因为您的类继承自
System.Web.UI.Page
)。我为新代码创建了一个新页面,并出现错误[link]。谢谢
void Page_Load(object sender,EventArgs e) {
    Response.Write(includer("header.html"));
    //irrelevant code
    if ('stuff happens') {
        returnError();
    }
    Response.Write(includer("footer.html"));
}
public static void returnError
public static string includer
if ('stuff happens') {
    this.returnError();
}