简体   繁体   中英

no suitable method found to override C# when i call ToString

Why when I use this class(called TaxiStation) which is calls toString of Taxi Class:

public override string TaxiInformation(int i)
        {

            return taxiCollectionDrivers[i].ToString();

        }

ToString() of Taxi class:

public override string ToString()
        {
     string str;
     str = "Taxi ID: " + this.taxiId + "\nDriver Name: " + this.driverName + "\nPassengers " + this.numPass + "\nTotal Passengers: " + totalPassengers + "\nRate Per Kilometer: " + this.ratePerKilometer+
         "\n\n Available: " + this.available ; 
     return str;    
        }

It's show me the error no suitable method found to override? how do i solve it ?

I just suppose , considering that the message written can not be related to ToString(..) override, as it present in parent of all objects in CLR , in object , so I suppose it's all about

public override string TaxiInformation(int i){
   ....
}

method. To be able override a method you have to have in the base class of the type where this method is overridden the same method (same signature) declared like virtual or abstract .

An hypothetic example:

public class TaxiStation
{
  ..... 
    public virtual string TaxiInformation(int i){
       ....
    }

}


public class Taxi : TaxiStation 
{
    public override string TaxiInformation(int i){
       ....
    }
}

The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.

...

The overridden base method must have the same signature as the override method .

MSDN: override (C# Reference)

For example:

public abstract class MyBaseClass
{
   public abstract void Foo(int i);
}

or

public class MyBaseClass
{
   public virtual void Foo(int i)
   {
      // ...
   }
}

Another reason that a method is not available for overriding is because it has been marked as sealed in the base class:

public class ClassA // Inherited from object
{
    public sealed override string ToString()
    {
        return base.ToString();
    }
}

public class ClassB : ClassA
{
    // Compilation error!
    public override string ToString()
    {
        return base.ToString();
    } 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM