为什么Cast(CType/DirectCast)控件与隐式转换

 完颜777_870 发布于 2023-02-11 12:24

假设我在webforms GridViewRow中有一个控件...


在RowDataBound事件中,我可以使用以下任何方法访问控件.我一直以来一直使用DirectCast:

Protected Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gv.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow
            ' 1) Dim ltl_abc As Literal = DirectCast(e.Row.FindControl("ltl_abc"), Literal)
            ' 2) Dim ltl_abc As Literal = CType(e.Row.FindControl("ltl_abc"), Literal)
            ' 3) Dim ltl_abc As Literal = e.Row.FindControl("ltl_abc")

使用任何特定方法有什么好处吗?我猜DirectCast稍微有点效率,但可能容易出错,但隐式转换是否有任何危险(选项3)?

从历史上看,在我尝试为控件的属性实际赋值之前,我从未见过任何错误,这让我觉得这第一步不是那么重要吗?

请注意,这不是DirectCast与CType的讨论,更多的是关于在这里是否需要施法?

更新清晰

Protected Sub gv_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles gv.RowDataBound
    Select Case e.Row.RowType
        Case DataControlRowType.DataRow

            ' This works fine, but no explicit casting is done:
            Dim ltl_abc As Literal = e.Row.FindControl("ltl_abc") ' no (explicit) cast
            ltl_abc.Text = "Hello World"

            ' This also works until I try to access the object's properties
            Dim ltl_abc As Literal = DirectCast(e.Row.FindControl("NonExistentId"), Literal)

那么为什么开发人员应该投射(在这个例子中),或者这个例子过于简单?

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有