代码之家  ›  专栏  ›  技术社区  ›  Edward Tanguay

为什么C从重写属性而不是重写属性获取值?

  •  4
  • Edward Tanguay  · 技术社区  · 16 年前

    我怀疑下面要输出的代码:

    (我是SmartForm对象,正在使用SmartForm中的方法).xml

    相反,它输出:

    (我是一个SmartForm对象,正在使用item.xml中的方法)。

    为什么会这样?我怎样才能强迫C从 压倒一切 财产? 这就是我的原因 压倒一切 财产。

    using System;
    
    namespace TestInhersdk234
    {
        public class Program
        {
            static void Main(string[] args)
            {
                SmartForm smartForm = new SmartForm();
                Console.ReadLine();
            }
        }
    
        public class SmartForm : Item
        {
            public SmartForm()
            {
                Console.WriteLine(FullXmlDataStorePathAndFileName);
            }
    
            public new string GetItemTypeIdCode
            {
                get
                {
                    return String.Format("(I am a {0} object and using the method in SmartForm)", this.GetType().Name);
                }
            }
        }
    
        public class Item
        {
            public string FullXmlDataStorePathAndFileName
            {
                get
                {
                    return GetItemTypeIdCode + ".xml";
                }
            }
    
            public string GetItemTypeIdCode
            {
                get
                {
                    return String.Format("(I am a {0} object and using the method in Item)", this.GetType().Name);
                }
            }
        }
    }
    
    5 回复  |  直到 16 年前
        1
  •  6
  •   second    16 年前

    您需要添加 重写 重写方法的关键字?

        2
  •  13
  •   Jon B    16 年前

    你并不是真的压倒一切。你藏起来了。要覆盖:

    class MyBase
    {
        public virtual void foo() {}
    }
    
    class MyClass : MyBase
    {
        public override void foo() {}
    }
    
        3
  •  3
  •   John Rudy    16 年前

    未标记要重写的项的属性 virtual . 因此,当您在SmartForm中重新定义它们时,您只是“隐藏”它们,而不是实际覆盖它们。(此外,您还需要 override 智能窗体中的关键字。)

    退房 this guide .

        4
  •  0
  •   Skirwan    16 年前

    getitemtypeidcode不是虚拟的;您没有覆盖它,只是隐藏它。在这种情况下,执行哪个方法不是基于对象的动态类型,而是基于对象引用的静态类型。在fullXMLDatastorePathAndFileName中,“this”的静态类型是item,而不是smartForm,因此将调用getItemTypeIDCode的项实现。

        5
  •  0
  •   John Nicholas    16 年前

    基类中的属性应标记为虚拟

    继承类中的属性也应标记为重写

    另外,我不知道为什么关键字new出现在属性定义的代码中