سؤال

So I am learning how instances work and how to set them and such and I am wondering if I can output the variables of an instance without to output them separately.

Ex//

class Program
{
    static void Main(string[] args)
    {
        Person Ryan = new Person();
        Ryan.Age = 16;
        Ryan.Name = "Rynoh97";
    }
}
class Person
{
    public int Age = 0;
    public string Name = "";
} 

Now to output my age I need to do Console.WriteLine(Ryan.Age); and for my name I need Ryan.Name but is there a way to output them both at the same time without making something complex.

I've tried Ryan.ToString() but I get the location of the class for Person.

Any advice?

هل كانت مفيدة؟

المحلول

You can override ToString in the Person class and make it output however you want it to when you call ToString.

There's an example here:

http://msdn.microsoft.com/en-us/library/ms173154.aspx

نصائح أخرى

Apart from overriding ToString, you can also use String.Format:

string personDescription = String.Format("Name: {0}, Age: {1}", Ryan.Age, Ryan.Name);
Console.WriteLine(personDescription);

Console.WriteLine even comes with an overload to do this for you:

Console.WriteLine("Name: {0}, Age: {1}", Ryan.Age, Ryan.Name);

.ToString is generally fine, but you only get one override. If you need to display a "Person" multiple ways, this method is a bit more flexible. On the other hand, overriding ToString() becomes very useful when trying to display an object in something like a ListBox.

You can override the toString method to make it display whatever you want. Something like this.

public override string ToString()
    {
        return "Name: " + Name + " Age: " + Age;
    }

Then whenever you call the Ryan.toString() method, this will be displayed instead. Hope this helps.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top