2013-03-29 70 views
1

我做過類似的事情;如何在C#中使用通用列表來實現多用途?

var list; //-> i want to declare this list once time 
if (gvd.ID.Equals("gvAccountSetup")) 
{ 
    ClsAccountHead AccountHead = new ClsAccountHead(); 
    AccountHead.CampusId = cmbAccCampus.SelectedValue.ToInt32(); 
    // here i want to intialize the same list with other type 
    list = new List<ClsAccountHead>(); 
    list = AccountHead.AccountHeadListByCampusId(PageIndex + 1, PageSize); 
} 
else if (gvd.ID.Equals("gv_AccSubHead")) 
{ 
    ClsAccountSubHead AccountSubHead = new ClsAccountSubHead(); 
    AccountSubHead.HeadId = cmbSrchAccHead.SelectedValue.ToInt32(); 
    // here i want to intialize the same list with another type 
    list = new List<ClsAccountSubHead>(); 
    list = AccountSubHead.SubHeadGetListByHeadIdWithPaging(PageIndex, PageSize); 
} 

所以,我的問題是我怎樣寫一個列表(通用)這是聲明瞭一次,然後我可以通過multipe型與它;

回答

2

您可以簡單地創建一個「標籤」 ineterface並取得所有的類實現它,並且:

internal interface TagInterface { } // rename it as appreciated 

public class MyList<T> : List<T> where T : TagInterface { } 

var list = new MyList<ClsAccountHead>(); 

或非常簡單:

var list = new List<TagInterface>(); 
+0

如何使TagInterface ...? –

+0

Plz可以給我發送Interface –

+0

@ShahidIqbal我修改了答案 – 2013-03-29 06:07:03

1

只需使用的基類或接口項目爲ListT

var list = new List<BaseAccountHead>(); 

並確保您的類型擴展此類型:

class BaseAccountHead { } 
class ClsAccountHead : BaseAccountHead { } 
class ClsAccountSubHead : BaseAccountHead { } 
相關問題