0

我有两个派生自抽象泛型类的类,该类派生自 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. 
                */
            }
        }
    }
}

谢谢!

4

1 回答 1

2

“计算机科学中的任何问题都可以通过另一个层次的间接来解决。”

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>to进行转换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) {
          ...
       }
    }
}
于 2012-05-16T16:33:15.857 回答