2013-11-05 27 views
0

如果非要定義爲個人一類概括的人,只是包含了人的,像這樣的列表中的字段和的人之一:OOP從數據庫讀取一類對象的列表

public class Person 
{ 
public Person(){} 
public int personID {get;set;} 
public string name {get;set;} 
public string address {get;set;} 
} 



public class People 
{ 
    public People(){} 

    public List<Person> peoples {get;set;} 

    public List<Person> getPeople() 
    { 
    List<Person> p = new List<Person>(); 
    //create database connection 
    SqlConnection conn = new SqlConnection() 
    string SQLSelct = @"select * from people where active=1"; 
    //open datareader 


    Person onePerson = new Person(); 
    //write data to each property type and add data to list 

    p.Add(onePerson); 
    return p; 

    } 

} 

調用從數據庫獲取人員的數據庫方法。

static void main(string[] args) 
{ 
    People p = new People(); 
    p.getPeople(); 


} 

這是我如何在OOP方面做到這一點。 我剛開始使用我的編碼這些技術通常我會做這個以獲取列表:從人民類

取出getPeople(),併爲此在主:

 List<Person> people = getPeople(); 

static void main(string[] args) 
{ 
    List<Person> people = getPeople(); 
} 


    private static List<Person> getPeople() 
    { 
     List<Person> p = new List<Person>(); 
     //create database connection 
     //open datareader 
     //load data into list 

     Person onePerson = new Person(); 

     p.Add(onePerson); 
     return p; 

    } 
+3

這個問題似乎是脫離主題,因爲它屬於Programmers.SE或CodeReview.SE –

+0

我想我真正的問題是當我試圖從OOP中檢索數據形式的數據庫時,我在類方法中執行此方法像我上面展示的那樣? – Jt2ouan

回答

1

首先,你可以刪除空的構造函數,因爲它們什麼都不做。然後,如果它只是一個帶有數據庫讀取方法的列表,請不要打擾創建People類。你的Person類很好。不過,我認爲你是從錯誤的一方開始的。

你應該從決定你的程序的功能開始:也許你有一個機場,你正在處理時間表。在那種情況下,從機場開始。決定它的功能。如果零件是一個邏輯組,例如一個Schedule或一個Plane,你就有很好的機會去上課。確保你的方法很好地命名; getPeople並沒有真正說明目的。考慮LoadPeopleFromDatabase

最終,您的目標應該是以易於將邏輯與不相關邏輯分開的方式爲您的問題域建模。