2012-03-10 3 views
0

이것은 '끝내지 못했습니다'라는 결과를 초래할 수 있습니다.하지만 내 특정 쿼리에 대한 답을 찾지 못했습니다.변수를 사용하여 객체를 초기화하기

내 문제는 학생들의 세부 사항을 담고있는 구조체를 가지고 있습니다. 이제 두 명의 학생이 있습니다. 하나는 Mike이고 다른 하나는 Dave라고하며, 각자의 세부 정보를 얻고 싶습니다. 내 구조체에 메소드가 있습니다. 그래서 :

public struct student{ 
    public String name, course; 
    public int year, studentno; 

    public void displayDetails(){ 
     Console.WriteLine("Name: "+name); 
     Console.WriteLine("Course: "+course); 
     Console.WriteLine("Student Number: "+studentno); 
     Console.WriteLine("Year of Study: "+year); 
     Console.WriteLine("\n\nPress any key to Continue...."); 
     Console.ReadKey(); 
    } 
} 

세부 사항을 표시하려면 다음 중 하나를 사용하십시오. Mike.displayDetails(); 또는 Dave.displayDetails();

이름에 대한 사용자 입력을 요청한 다음 그 이름을 사용하여 올바른 학생을 얻을 수있는 방법이 있습니까? 이 행할 수,

surname.displayDetails(); 

올바른 학생을 표시 예를 들어 내가 사용하려는 :

Console.Write("Please enter students name: "); 
String surname = Console.ReadLine(); 

을하고 어떻게 든 사용할 수 있습니까?

답변

6

문자열 유형에 extension method을 사용할 수는 있지만 권장하지는 않습니다. LINQ를 사용하여 학생 컬렉션에 대해 성을 가진 학생을 찾으십시오.

List<Student> students 
    = new List<Student> 
     { 
     new Student { Surname = "Smith" }, 
     new Student { Surname = "Jones" } 
     }; 

Student studentJones = students.FirstOrDefault(s => s.Surname == "Jones"); 

다른 점은주의해야 : 당신이 방법 및 유형 이름에 너무

  • 사용 PascalCase을 할 수있는 좋은 이유가없는

    • 클래스가 아닌 구조체를 사용
    • 사용하지 마십시오 대신 공개 속성을 사용하십시오.
  • 3

    사전에 입력 할 수 있습니다.

    Dictionary<string, Student> dict = new Dictionary<string, Student>(); 
    dict.Add("Dave", Dave); 
    dict.Add("Mike", Mike); 
    string surname = Console.ReadLine(); 
    dict[surname].DisplayDetails(); 
    

    BTW는, 사전 검색에서 빠르게 통상 (O (1))가 수행 FirstOrDefault리스트 (O (N))를 통해보고보다.

    0

    클래스를 만들고 KeyedCollection에서 파생됩니다. 키를 학생의 이름으로 설정하십시오. 각 학생이 컬렉션에 추가되면 다음 번호로 전화하면됩니다.

    Console.Write(myCollection[surname].DisplayDetails()); 
    
    
    
    public class Students : KeyedCollection<string, Student> 
    { 
        // The parameterless constructor of the base class creates a 
        // KeyedCollection with an internal dictionary. For this code 
        // example, no other constructors are exposed. 
        // 
        public Students() : base() {} 
    
        // This is the only method that absolutely must be overridden, 
        // because without it the KeyedCollection cannot extract the 
        // keys from the items. The input parameter type is the 
        // second generic type argument, in this case OrderItem, and 
        // the return value type is the first generic type argument, 
        // in this case string. 
        // 
        protected override string GetKeyForItem(Student item) 
        { 
         // In this example, the key is the student's name. 
         return item.Name; 
        } 
    } 
    
    관련 문제