virtual properties

前端 未结 7 1436
迷失自我
迷失自我 2020-12-14 00:00

I have used and learned only virtual methods of the base class without any knowledge of virtual properties used as

class A
{
   public virtual ICollection<         


        
7条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 00:37

    In object-oriented programming, a virtual property is a property whose behavior can be overridden within an inheriting class. This concept is an important part of the polymorphism portion of object-oriented programming (OOP).

    look at the example below:

    public class BaseClass
    {
    
        public int Id { get; set; }
        public virtual string Name { get; set; }
    
    }
    
    public class DerivedClass : BaseClass
    {
        public override string Name
        {
            get
            {
                return base.Name;
            }
    
            set
            {
                base.Name = "test";
            }
        }
    }
    

    at the presentation level:

            DerivedClass instance = new DerivedClass() { Id = 2, Name = "behnoud" };
    
            Console.WriteLine(instance.Name);
    
            Console.ReadKey();
    

    the output will be "test" because the "Name" property has been overridden in the derived class(sub class).

提交回复
热议问题