问题描述:

class Person

{

public int age;

public string haircolor;

public string name;

}

class Program

{

static void skapaPerson(string name, string haircolor, int age) {

Console.Write("Vad är personens namn? ");

name = Console.ReadLine();

Console.Write("Hur gammal är personen?");

age = int.Parse(Console.ReadLine());

Console.Write("Vad är personens hårfärg? ");

haircolor = Console.ReadLine();

}

static void Main(string[] args)

{

Person Person1 = new Person();

skapaPerson(Person1.name, Person1.haircolor, Person1.age);

Console.Write("{0} {1} {2}", Person1.name, Person1.haircolor, Person1.age);

Console.ReadLine();

}

What I'm looking for is how to assign the values of the different class elements using the method, making me able to edit a specific element at any given time.

The write at the end was just for testing and at the current moment the write just returns "0" for me.

If able I would also like to know how to create new class elements using another method.

网友答案:

Instead of explicitly passing in each individual property, consider passing in the actual Person object to your method and setting the properties within your method :

static void skapaPerson(Person p) {
    Console.Write("Vad är personens namn? ");
    p.name = Console.ReadLine();
    Console.Write("Hur gammal är personen?");
    p.age = int.Parse(Console.ReadLine());
    Console.Write("Vad är personens hårfärg? ");
    p.haircolor = Console.ReadLine();
}

along with :

// Create an instance of your person
Person Person1 = new Person();
// Set it's properties
skapaPerson(Person1);

You can see an interactive example of this in action here.

网友答案:

your class should look like this

static Person skapaPerson()
{
    Person pResult = new Person(); //create new Person object here
    Console.Write("Vad är personens namn? ");
    pResult.name = Console.ReadLine();
    Console.Write("Hur gammal är personen?");
    pResult.age = int.Parse(Console.ReadLine());
    Console.Write("Vad är personens hårfärg? ");
    pResult.haircolor = Console.ReadLine();
    return pResult; //return object with entered data
}

static void Main(string[] args)
{
    Person Person1 = skapaPerson(); //Person 1 is the result of skapaPerson()
    Console.Write("{0} {1} {2}", Person1.name, Person1.haircolor, Person1.age);
    Console.ReadLine();
}

if you want to gather data within your skapaPerson method you can create a Person object in there and return it

相关阅读:
Top