C# ASPX访问母版页功能
我试图从另一个ASPX页面访问位于母版页代码后面的函数,如下所示 Main.master.cs:C# ASPX访问母版页功能,c#,asp.net,C#,Asp.net,我试图从另一个ASPX页面访问位于母版页代码后面的函数,如下所示 Main.master.cs: public partial class Main : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { ... } public static bool test() { return true; } }
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
...
}
public static bool test()
{
return true;
}
}
Product.aspx:
<%@ Page Language="C#" MasterPageFile="~/Main.master" EnableEventValidation="false"
AutoEventWireup="true" ValidateRequest="false" CodeFile="Product.aspx.cs" Inherits="Common_Product" Title="Product" %>
...
<asp:Label id="test123" runat="server" />
这将导致编译器错误:
Compiler Error Message: CS0176: Member 'Main.test()' cannot be accessed with an instance reference; qualify it with a type name instead
在这种情况下有什么问题
谢谢。试试这个:
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
...
}
public bool test()
{
return true;
}
}
Error说得很清楚,您不能使用实例引用访问静态方法。 您需要这样做:
test123.Text = "yo | " + Main.test();
然而,我不确定把这样的方法放到你的主页上是否是最好的做法。。。您应该创建一个新类并使用它。更改测试,使其成为属性
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
...
}
public Property bool test()
{
get { return true; }
}
}
不能使用实例对象访问静态方法 应该是
Main.test();
您的
test
方法是用static
关键字定义的。这里有一些链接可以了解更多:,@CAbbott,我相信这只是一个输入错误,你不能定义这样的方法。。。
Main.test();