开发者

Whats wrong with this C# generic function call?

I have a generic function

private void Pul开发者_开发知识库lDataAndBindGrid<T>(GridView grid, List<T> list)
{
    databaseFields = list;
    //BindGrid<T>(grid, list);
}

Its called like

private static List<FieldMaster> databaseFields;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        PullDataAndBindGrid<FieldMaster>(FieldsGrid, manager.GetAddedFields());
    }
}

And I get compile time error as

Cannot implicitly convert type 'System.Collections.Generic.List<T>' to 'System.Collections.Generic.List<MailCampaign.DAL.FieldMaster>'

Update:

The declaration of manager.GetAddedFields() is public List<FieldMaster> GetAddedFields()

What could be wrong?


The culprit is this line

databaseFields = list;

where databaseFields is of type List<FieldMaster>, and list is of type List<T>

Since you don't know what T will be until you actually call the function, you can't assume that something of type List<T> can be assigned to a variable of type List<FieldMaster>. Either get rid of the generics in that function, or apply generics to your entire class - either way, make sure everything is guarenteed to have the same type.


As your method is generic, you cannot push any generic List type into the strongly typed databaseFields field as you are doing here:

databaseFields = list;

You should reconsider your reasons for making this method generic. If this is required then I suggest doing a check to ensure you have the right type then casting like so:

private static void PullDataAndBindGrid<T>(List<T> list)
{
    if (list is List<FieldMaster>)
    {
        databaseFields = list as List<FieldMaster>;    
    }       
    //BindGrid<T>(grid, list);
}


Check the return type of the GetAddedFields() method on that manager object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜