2012-05-05 37 views
1

我沒有什麼問題。 在我的代碼的第一個方法中,我已經將關於學生的數據從txt文件加載到List集合。還有更多類型的學生(班PrimaryStudent,SecondaryStudent,HightSchoolStudent,大學學生,ExternStudent等) 現在,在其他方法我要節省每樣的學生到不同的目錄。我的問題在於,我在該界面中的所有對象中都有對象。現在我該怎麼區分呢?我該怎麼做才能區分所有類型的學生?請幫忙。將對象轉換爲正確的類型

+0

您使用的是通用名單? –

+0

是的。我正常使用它。 – user35443

+0

羽絨服是我尋找的解決方案。如果要存儲普通學生以及 – user35443

回答

2

如果列表是通用的,即List<Student>你可以做到以下幾點:

List<PrimaryStudent> primaryStudents = myStudentList.OfType<PrimaryStudent>().ToList(); 

如果您的列表是不通用的,你可以像這樣把它們分開:

foreach(var s in myStudentList) 
{ 
    if(s is PrimaryStudent) 
    { 

    // add to PrimaryStudents list 
    } 
    else if(s is SecondaryStudent) 
    { 

    ... 
    } 
} 
+0

OfType不起作用,因爲OfType 將返回,不僅學生,而且主要和SecondaryStudents。 OfType LINQ運算符也會共享相同的問題。下面看看我的解決方案如何以安全的方式完成這項工作。 –

1

看一看在c#中的is keyword

例子:

List<IStudent> students = new List<IStudent>(); 

students.Add(new PrimaryStudent()); 
students.Add(new SecondaryStudent()); 
students.Add(new HightSchoolStudent()); 

foreach (IStudent student in students) 
{ 
    if (student is PrimaryStudent) 
    { 
     Console.WriteLine("This was a PrimaryStudent"); 
    } 
    else if (student is SecondaryStudent) 
    { 
     Console.WriteLine("This was a SecondaryStudent"); 
    } 
    else if (student is HightSchoolStudent) 
    { 
     Console.WriteLine("This was a HightSchoolStudent"); 
    } 
} 

Console.Read(); 

輸出:

This was a PrimaryStudent 
This was a SecondaryStudent 
This was a HightSchoolStudent 
+0

如果您不想存儲作爲小學和中學學生基礎課程的正規學生,那麼is關鍵字才起作用。 –

+0

如果您將if語句放在所有其他if語句的下面,它會起作用。 – GameScripting

+0

這是真的,但這個代碼很難保持和擴展。我不想每次都爲新的學生類型編寫額外的代碼。我的通用解決方案不需要知道哪些學生類型存在。它只是按類型對它們進行分組。 –

1

您可以首先從收集獲得所有學生的類型,然後按類型保存到它們的最終位置。此處介紹的解決方案不使用is或OfType方法,因爲如果要將Students,PrimaryStudents和SecondaryStudents存儲在不同的文件夾中,則這些運算符無法正常工作。

換句話說,如果你想要把你的基類的實例differntly(例如保存到不同的充文件夾),你需要放棄OfType和運營商是直接,但檢查的類型。

class Student { } 
class PrimaryStudent : Student { } 
class SecondaryStudent : Student { } 

private void Run() 
{ 
    var students = new List<Student> { new PrimaryStudent(), new PrimaryStudent(), new SecondaryStudent(), new Student() }; 
    Save(@"C:\University", students); 
} 

private void Save(string basePath, List<Student> students) 
{ 
    foreach (var groupByType in students.ToLookup(s=>s.GetType())) 
    { 
     var studentsOfType = groupByType.Key; 
     string path = Path.Combine(basePath, studentsOfType.Name); 
     Console.WriteLine("Saving {0} students of type {1} to {2}", groupByType.Count(), studentsOfType.Name, path); 
    } 

} 

Saving 2 students of type PrimaryStudent to C:\University\PrimaryStudent 
Saving 1 students of type SecondaryStudent to C:\University\SecondaryStudent 
Saving 1 students of type Student to C:\University\Student 
相關問題