2015-07-05 2 views
1

Я хочу напечатать значения из метода GetStudentInformation() с помощью метода PrintStudentDetails (строка first, string last, string birthday). Пожалуйста, просмотрите приведенный ниже код:Как напечатать несколько значений в методе C#?

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace Module3_HomeWork 
{ 
    class Program 
    { 
     static void GetStudentInformation() 
     { 
      Console.WriteLine("Enter the student's first name: "); 
      string firstName = Console.ReadLine(); 
      Console.WriteLine("Enter the student's last name: "); 
      string lastName = Console.ReadLine(); 
      Console.WriteLine("Enter the student's birthdate: "); 
      DateTime birthdate = Convert.ToDateTime(Console.ReadLine()); 
      Console.WriteLine("Enter the student's address line 1: "); 
      string add1 = Console.ReadLine(); 
      Console.WriteLine("Enter the student's address line 2: "); 
      string add2 = Console.ReadLine(); 
      Console.WriteLine("Enter the student's city: "); 
      string city = Console.ReadLine(); 
      Console.WriteLine("Enter the student's state: "); 
      string state = Console.ReadLine(); 
      Console.WriteLine("Enter the student's zip code: "); 
      int zip = Convert.ToInt32(Console.ReadLine()); 
      Console.WriteLine("Enter the student's country: "); 
      string country = Console.ReadLine(); 
     } 
     static void PrintStudentDetails(string first, string last, string birthday) 
     { 
      Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday); 
     } 
     static void Main(string[] args) 
     { 
      GetStudentInformation(); 
      PrintStudentDetails(first, last, birthday); 
     } 

     public static string first { get; set; } 

     public static string last { get; set; } 

     public static string birthday { get; set; } 
    } 
} 

Как я могу печатать значения, используя только методы не класса? Я исследовал его и узнал о out и ref, любая помощь или руководство будут высоко оценены.

С уважением

+0

использовать свойства вместо локальной переменной –

ответ

2

Если все, что вы хотите, чтобы ввести имя, фамилию и дату рождения, а затем выводить их, вы можете изменить следующие три линии:

string firstName = Console.ReadLine(); 
string lastName = Console.ReadLine(); 
DateTime birthdate = Convert.ToDateTime(Console.ReadLine()); 

к следующему:

first = Console.ReadLine(); 
last = Console.ReadLine(); 
birthday = Convert.ToDateTime(Console.ReadLine()); 

тогда ваша программа должна работать так, как вы ожидаете.

Но так как вы упомянули out и ref, возможно, то, что вы действительно хотите следующее:

class Program 
{ 
    static void GetStudentInformation(out string first, out string last, out string birthday) 
    { 
     Console.WriteLine("Enter the student's first name: "); 
     first = Console.ReadLine(); 
     Console.WriteLine("Enter the student's last name: "); 
     last = Console.ReadLine(); 
     Console.WriteLine("Enter the student's birthdate: "); 
     birthday = Convert.ToDateTime(Console.ReadLine()); 
    } 
    static void PrintStudentDetails(string first, string last, string birthday) 
    { 
     Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday); 
    } 
    static void Main(string[] args) 
    { 
     string first, last, birthday; 
     GetStudentInformation(out first, out last, out birthday); 
     PrintStudentDetails(first, last, birthday); 
    } 
} 
1

Я не совсем уверен, что вы имели в виду значения печати только метод не класс. Но я думаю, ниже пример может помочь вам.

void PrintDetails(ref string s1, ref string s2, ref string s3) 
{ 
    s1 = "Some text goes here"; 
    s2 = myNumber.ToString(); 
    s3 = "some more text"; 
} 

Теперь при вызове этой функции просто использовать ниже синтаксис:

public void SomeOtherFunction() 
{ 
    string sMyValue1 = null; 
    string sMyValue2 = null; 
    string sMyValue3 = null; 

    PrintDetails(sMyValue1, sMyValue2, sMyValue3); 
    //Now you have all the values inside your local variable. 
} 
0

Использование out или ref ключевого слова поможет вам вернуть несколько значений из метода, если вы действительно хотите, чтобы сделать это, что но использование свойств, вероятно, является лучшим решением. В любом случае, это то, как он будет выглядеть, используя ключевое слово out:

static void GetStudentInformation(out string firstName, out string lastName, out DateTime birthDate, 
    out string add1, out string add2, out string city, out string state, out int zip, out string country) 
{ 
    Console.WriteLine("Enter the student's first name: "); 
    firstName = Console.ReadLine(); 
    Console.WriteLine("Enter the student's last name: "); 
    lastName = Console.ReadLine(); 
    Console.WriteLine("Enter the student's birthdate: "); 
    birthDate = Convert.ToDateTime(Console.ReadLine()); 
    Console.WriteLine("Enter the student's address line 1: "); 
    add1 = Console.ReadLine(); 
    Console.WriteLine("Enter the student's address line 2: "); 
    add2 = Console.ReadLine(); 
    Console.WriteLine("Enter the student's city: "); 
    city = Console.ReadLine(); 
    Console.WriteLine("Enter the student's state: "); 
    state = Console.ReadLine(); 
    Console.WriteLine("Enter the student's zip code: "); 
    zip = Convert.ToInt32(Console.ReadLine()); 
    Console.WriteLine("Enter the student's country: "); 
    country = Console.ReadLine(); 
} 
static void PrintStudentDetails(string first, string last, string birthday) 
{ 
    Console.WriteLine("{0} {1} was born on: {2}", first, last, birthday); 
} 

static void Main(string[] args) 
{ 
    string firstName, lastName, add1, add2, city, state, country; 
    DateTime birthDate; 
    int zip; 

    GetStudentInformation(out firstName, out lastName, out birthDate, out add1, out add2, out city, out state, out zip, out country); 
    PrintStudentDetails(firstName, lastName, birthDate.ToShortDateString()); 
} 

Вы также могли бы заменить все из ключевых слов с ref ключевых слов, и вы получите тот же эффект. Вам просто нужно инициализировать переменные до некоторого значения, прежде чем передавать их с помощью метода GetStudentInformation.

Смежные вопросы