Why does C # take value from an overridden property instead of an overriding property?

I would suspect the code below for output:

(I am a SmartForm object and use the method in SmartForm) .xml

instead, it produces:

(I am a SmartForm object and use the method in Item) .xml

Why? How can I get C # to accept a value from an overriding property? That is why I am redefining a property.

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); } } } } 
+4
source share
5 answers

Do you need to add the override keyword to the override method?

+6
source

You don't really redefine. You're hiding. To cancel:

 class MyBase { public virtual void foo() {} } class MyClass : MyBase { public override void foo() {} } 
+13
source

The properties of the element you want to override are not marked virtual . As a result, when you override them in SmartForm, you simply "hide" them, and not actually override them. (In addition, you will need the override keyword in SmartForm.)

Check this guide .

+3
source

GetItemTypeIdCode is not virtual; you do not redefine it, you just hide it. In this case, which method is executed is not based on the dynamic type of the object, but on the static type of the object reference. Inside FullXmlDataStorePathAndFileName, the static type 'this' is Item, not SmartForm, so the GetItemTypeIdCode implementation is called.

0
source

a property in the base class should be marked as virtual

also the property in the inherited class should be marked as an override

Also I'm not sure why the new keyword appears in your code in a property definition

0
source

Source: https://habr.com/ru/post/1285966/


All Articles