代码之家  ›  专栏  ›  技术社区  ›  MatthewMartin muthu

基类能看到派生类的受保护字段吗?

  •  0
  • MatthewMartin muthu  · 技术社区  · 14 年前

    public class BasePage:Page
    {
        public void DoSomethingWithDerivedPageControl()
        {
            //foo is always null.
            Control foo = FindControl("Foo");
        }
    }
    
    public class DerivedPage : BasePage
    {
        //In real life, this is the code generated .aspx.designer.cs file.
        protected Label Foo;
    }
    
    4 回复  |  直到 14 年前
        1
  •  4
  •   Jon Skeet    14 年前

    FindControl 不使用字段-它使用已添加到页面的控件,并检查其ID。

    可能您的控件在 DoSomethingWithDerivedPageControl

    如果你能告诉我们你真正想要达到的目标,那会很有帮助。。。如果所有派生类型都应有一个名为 Foo

        2
  •  2
  •   Michael Meadows    14 年前
    public abstract class BasePage:Page 
    { 
        abstract protected Label Foo {get;}
        public void DoSomethingWithDerivedPageControl() 
        { 
            Control foo = this.Foo;
        } 
    } 
    
    public class DerivedPage : BasePage 
    { 
        override protected Label Foo { get; set;} 
    } 
    

    现在,我怀疑这并不能完全满足你的需要。但是,基类不知道它的孩子。在子类中查找随机场的唯一方法是忽略它们是基/派生的事实,并使用它的反射,就好像它是一个不相关的类一样。

        3
  •  1
  •   Buggieboy    14 年前

    毫无疑问,引用子成员的基类无法编译,因为基类定义不知道该成员。

        4
  •  0
  •   Gary L Cox Jr    14 年前

    哇,你这么做真吓人。基类不应该知道任何关于派生类的信息。