How to call a parent class's method from child class in c#?
I have a master page with a method I use a lot from content page code behinds. In those code behinds, I have a method that gets duplicated a lot, so I thought I'll put it in something I can inherit from. Unfortunately, I now can't call the method in my master page code behind from the base class. I think I should know how and I'm probably being pretty stupid today but I can't figure it out.
Here's some code! Please ignore any howling errors, I just typed this off the top of my head :)
Master Page Code-behind
public partial class Site : MasterPage
{
public void MyMethod()
{
// Do Something...
}
}
Content (Child) Page
Declarative
<%@ MasterType VirtualPath="~/Site.Master" %>
Code-behind
Works
public class Test : Page
{
protected void Page_Load(object sender, EventArgs e)
{
this.Master.MyMethod();
}
}
Does Not Work
public class Test : TestClass
{
protected void Page_Load(object sender, EventArgs e)
{
OtherMethod();
}
}
public class TestClass : Page
{
public void OtherMethod()
{
this.Master.MyMethod();
}
}
Now, looking at it, I intuitively know "this.Master" can't work but I don't have any lightbulbs going off for an answer. How do I get the reference开发者_运维知识库 to my master page method back?
Thanks, Richard
You have to cast to the the type of the your MasterPage class first (in this case Site) and then you can call the public methods defined within the code behind class ...
public class TestClass : Page
{
public void OtherMethod()
{
((Site) this.Master).MyMethod();
}
}
You should cast this.Master to Site :
((Site)this.Master).MyMethod();
You have to cast this.Master to the type Site in order to access methods defined on Site : MasterPage.
public class TestClass : Page
{
public void OtherMethod()
{
((Site)this.Master).MyMethod();
}
}
精彩评论