Casting to generic type fails in c#

我与影子孤独终老i 提交于 2019-12-12 18:44:18

问题


I'd wish to save some coding by being able to create a dynamic GetControl method. My ideas is something like this

private T GetControl<T>(ASPxGridView control, string element)
{
    var returnedElement = (T)control.FindEditFormTemplateControl(element);
    return returnedElement;
}

Which I call with

var myElement = GetControl<ASPxTextBox>(myGridView, "UserId");

But, this fails miserably:

Cannot convert type 'System.Web.UI.Control' to 'T'

Any advices?


回答1:


Try adding a generic constraint:

private T GetControl<T>(ASPxGridView control, string element) where T : Control
{
    var returnedElement = (T)control.FindEditFormTemplateControl(element);
    return returnedElement;
}



回答2:


You can circumvent type safety by casting via object:

var returnedElement = (T)(object)control.FindEditFormTemplateControl(element);

Furthermore, I would constrain your generic type to Web.UI.Control, if only for the purpose of self-documentation:

private T GetControl<T>(ASPxGridView control, string element)
    where T: System.Web.UI.Control
{
    return (T)control.FindEditFormTemplateControl(element);
}


来源:https://stackoverflow.com/questions/7269967/casting-to-generic-type-fails-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!