1

我做过类似的事情;

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);
}

所以,我的问题是我如何编写一个声明一次的列表(通用),然后我可以用它传递多重类型

4

2 回答 2

2

您可以简单地创建一个“标记”接口并让您的所有类都实现它,并且:

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>();
于 2013-03-29T05:56:51.043 回答
1

List只需使用项目的基类或接口作为T

var list = new List<BaseAccountHead>();

并确保您的类型扩展了这种类型:

class BaseAccountHead { }
class ClsAccountHead : BaseAccountHead { }
class ClsAccountSubHead : BaseAccountHead { }
于 2013-03-29T06:02:16.720 回答