是否必须将 Label 更改为 Control 以避免可能的运行时错误?

Is it imperative that I change Label to Control to avoid a possible runtime error?

在尝试净化继承的遗留 VB.NET / ASP 项目时,我正在重新整理它,它告诉我,“ 转换 'System.Web.UI.Control' 到 'System.Web.UI.WebControls.Label'" 在这一行:

Dim _UserNameLabel As Label = PortalLogin.FindControl("UserNameLabel")

...但是当我默认了让它改成这样:

Dim _UserNameLabel As Control = PortalLogin.FindControl("UserNameLabel")

...这里的 "Style" 属性 变红了:

_UserNameLabel.Style("color") = dt1.Rows(0)("TextBoxColor")

有没有其他方法可以提供 Label/Control 颜色,我是最好忽略 Resharper 的建议,还是什么?

正确的选项是:

Dim _UserNameLabel = DirectCast(PortalLogin.FindControl("UserNameLabel"), Label)

FindControl 返回的 Control 引用被转换为类型 Label,然后您可以访问特定于类型 Label 的成员。 Option Infer On 允许从其初始化表达式推断出 UserNameLabel 变量的类型。使用 Option Infer Off 你需要写:

Dim _UserNameLabel As Label = DirectCast(PortalLogin.FindControl("UserNameLabel"), Label)

为了清楚起见,有些人还是喜欢这样做。类型推断通常很方便但不是必需的。需要的地方是使用 LINQ 查询返回的匿名类型。