Is it possible to get c# to use method overload of most specific type rather than base type?

前端 未结 4 1339
暖寄归人
暖寄归人 2020-12-11 18:33

If you have a method which is overloaded with a derived type, the method called at run-time depends on the type of your variable, even if the underlying object is actually o

4条回答
  •  情深已故
    2020-12-11 19:19

    public class Processor
    {
        public string Compose(BaseClass item)
        {
            return item.Compose();
        }
    }
    
    public class BaseClass
    {
        public string Foo { get; set; }
    
        public virtual string Compose()
        {
            return Foo;
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public string Bar { get; set; }
    
        public override string Compose()
        {
            return base.Compose() + Bar;
        }
    }
    

提交回复
热议问题