I have two classes that are derived from an abstract generic class, which is derived from System.Web.UI.Page. I have a System.Web.UI.MasterPage that may or may not be the master for either of my two derived page classes, or System.Web.UI.Page.
The problem is that the generic class has a property that I need to access in my MasterPage, but I don’t know any elegant way to get it.
Here is an example…
Content types:
public abstract class Fruit
{
public int ID { get; set; } //Just an identifier
}
public class Apple : Fruit { }
public class Banana : Fruit { }
Pages:
public abstract class FruitPage<T> : System.Web.UI.Page where T : Fruit
{
public T MyFruit { get; set; }
}
public class ApplePage : FruitPage<Apple> { }
public class BananaPage : FruitPage<Banana> { }
Master:
public partial class FoodMaster : System.Web.UI.MasterPage
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
if (this.Page is FruitPage<Fruit>) //I know this is wrong
{
if ((this.Page as FruitPage<Fruit>).MyFruit.ID <= 0) //This too
{
/*
I want to get here (this.Page being an ApplePage or BananaPage).
Basically... if ID<=0 then it is a new (unsaved) "fruit",
and I need to change some MasterPage GUI accordingly.
*/
}
}
}
}
Thank you!
“Any problem in computer science can be solved with another level of indirection.”
You could also shadow
MyInnerFruit/MyFruit– but it’s easier to understand without.If you’re using .NET 4, you can also use a covariant interface to basically allow casts from
FruitPage<Apple>toFruitPage<Fruit>: