【发布时间】:2012-05-16 16:14:11
【问题描述】:
我有两个派生自抽象泛型类的类,该类派生自 System.Web.UI.Page。我有一个 System.Web.UI.MasterPage,它可能是也可能不是我的两个派生页面类或 System.Web.UI.Page 的主页面。
问题是泛型类有一个我需要在我的 MasterPage 中访问的属性,但我不知道任何优雅的方法来获取它。
这是一个例子......
内容类型:
public abstract class Fruit
{
public int ID { get; set; } //Just an identifier
}
public class Apple : Fruit { }
public class Banana : Fruit { }
页数:
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> { }
大师:
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.
*/
}
}
}
}
谢谢!
【问题讨论】:
-
您放在
FoodMaster中的代码确实属于FruitPage...那么您就不会有这个问题。它永远不会适用于任何其他情况。 -
我也想过这个问题,但我可能应该提到这一点,我使用的是嵌套母版。
FoodMaster实际上是FoodFruitMaster的“父级”。我曾考虑向FoodMaster添加一个方法并从页面调用该方法,但它必须通过FoodFruitMaster冒泡。我认为这很草率。