简体   繁体   中英

C# Calling ToString in class by ToString in other class

I have 2 classes. My question is, how can I call ToString from first class called Racer in my second class called Time.

Simplified version: class B To string (return class A ToString + something from class B)

class Racer
{
    public string name, surname;


    public void ReadingSeparatorsRacer(string line) //Rozdělení separatorem
    {

        char[] separators = new char[] { ';' };
        string[] field = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);

        surname = field[0]; //Příjmení
        name = field[1]; //Jméno
    }

    public override string ToString()
    {
        return surname + name;
    }           
}

class Time
{
    DateTime startTime, finishTime, result;

    public void ReadingSeparatorsTime(string line)
    {
        char[] separators = new char[] { ';', ':', '.' };
        string[] field = line.Split(separators, StringSplitOptions.RemoveEmptyEntries);
    }

    public override string ToString()
    {
        string s = Racer.ToString

        return "" result;

    }
} 

Iam thinking about something like this:

public override ToString()
{
 return Racer.ToString + result;
}

But sadly, this does not work :(

Any ideas?

Thanks for help

As ToString() is not static, you can't call Racer.ToString().

You have to instanciate a Racer object an then call ToString() on it.

Edit: this probably nearer to what you are intending:

class Racer
{
    public string name, surname;
    public Time Time { get; set; }

    public override string ToString()
    {
        return surname + name + "(" + Time.ToString() + ")";
    }           
}

class Time
{
    DateTime startTime, finishTime, result;

    public override string ToString()
    {
        TimeSpan elapsedTime = finishTime - startTime;
        return elapsedTime.ToString();
    }
} 

Each Racer was a Time property which represents how long they took to run the race. The Racer.ToString method calls the Time.ToString method to include the race time, along with the Racer's name.

Generally, the easiest way to get self-maintainable ToString methods is to use a library for just exactly that. eg. from https://github.com/kbilsted/StatePrinter/blob/master/doc/AutomatingToStrings.md

class AClassWithToString
{
  string B = "hello";
  int[] C = {5,4,3,2,1};

  // Nice stuff ahead!
  static readonly Stateprinter printer = new Stateprinter();

  public override string ToString()
  {
    return printer.PrintObject(this);
  }
}

notice how the ToString will automatically update itself when you introduce new fields into the class.

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