我有两个派生自抽象泛型类的类,它派生自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.
*/
}
}
}
}
谢谢!
答案 0 :(得分:2)
"Any problem in computer science can be solved with another level of indirection."
public class FruitPage : System.Web.UI.Page {
public Fruit MyInnerFruit { get; protected set; }
}
public abstract class FruitPage<T> : FruitPage where T : Fruit
{
public T MyFruit {
get { return (T)MyInnerFruit; }
set { MyInnerFruit = value; }
}
}
public partial class FoodMaster : System.Web.UI.MasterPage {
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
var fruitPage = this.Page as FruitPage;
if (fruitPage != null && fruitPage.MyInnerFruit.ID <= 0) {
...
}
}
}
你也可以隐藏MyInnerFruit
/ MyFruit
- 但没有它就更容易理解。
如果你使用的是.NET 4,你也可以使用协变界面来基本上允许从FruitPage<Apple>
到FruitPage<Fruit>
的强制转换:
public interface IFruitPage<out T> where T : Fruit {
public T MyFruit { get; }
}
public class FruitPage<T> : Page, IFruitPage<T> where T : Fruit {
public T MyFruit { get; set; }
}
public class FoodMaster : MasterPage {
protected override void OnLoad(EventArgs e) {
base.OnLoad(e);
var fruitPage = this.Page as IFruitPage<Fruit>;
if (fruitPage != null && fruitPage.MyFruit.ID <= 0) {
...
}
}
}