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

前端 未结 4 1343
暖寄归人
暖寄归人 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:11

    First of all the reason you are getting the result you are getting the result you are getting is because of you specifically declared theDerivedObject as DerivedClass therefor it will go DerivedClass as parameter and with (BaseClass) theDerivedObject) you bassically just told the compiler (correct me if im wrong with compiler) or program to take the method with the parameter BaseClass

    What you want to do is one of the following options

    Number 1:

    public class Processor
    {
        public string Compose(BaseClass item)
        {
            if (item is DerivedClass)
                return Compose((DerivedClass) item);
            return item.Foo;
        }
    
        public string Compose(DerivedClass item)
        {
            return item.Foo + item.Bar;
        }
    }
    

    Number 2

    public class Processor
    {
        public string Compose(BaseClass item)
        {
            if (item is DerivedClass)
            {
                var derived = (DerivedClass) item;
                return derived.Foo + derived.Bar;
            }
            return item.Foo;
        }
    }
    

    Or you might want to overide ToString()

    public class Processor
    {
        public string Compose(BaseClass item)
        {
            var @class = item as DerivedClass;
            return @class?.ToString() ?? item.ToString();
        }
    }
    
    public class BaseClass
    {
        public string Foo { get; set; }
    
        public override string ToString()
        {
            return Foo;
        }
    }
    
    public class DerivedClass : BaseClass
    {
        public string Bar { get; set; }
    
        public override string ToString()
        {
            return Foo + Bar;
        }
    }
    

    If you are not using C#6.0 then Processor will be the following

    public class Processor
    {
        public string Compose(BaseClass item)
        {
            var @class = item as DerivedClass;
            if (@class != null)
            {
                return @class.ToString();
            }
            return item.ToString();
        }
    }
    

提交回复
热议问题