自定义 属性 不是控件 [vb.net] 的成员

Custom Property is not a member of Control [vb.net]

我是 vb.net 的新手,想知道我是否做对了。

在我的程序中,我创建了一个自定义控件 (CustomControl),它有一个自定义 属性 (CustomProperty)。

在程序中,我有一个 For Each 语句检查表单中的每个 CustomControl 并在满足特定条件时更改 CustomProperty 的值:

For Each _CustomControl as Control in Controls
    If TypeOf _CustomControl is CustomControl and [criteria met]
        _CustomControl.CustomProperty = value
    End If
next

每当我输入第三行时,它都会给我以下消息:

'CustomProperty' is not a member of 'Control'.

我知道我的习惯 属性 通常不属于 'Controls',我想知道我是否应该将某些内容添加到代码中,或者我是否应该将其输入其他代码方法。

感谢您提供的任何帮助。

您必须根据您的情况使用AndAlso

For Each _CustomControl As Control In Controls
    If TypeOf _CustomControl Is CustomControl AndAlso [criteria met]
        _CustomControl.CustomProperty = value
    End If
Next

您尝试访问默认 Control 上的 CustomProperty。使用 AndAlso 如果第一部分不为真,则不会评估条件的第二部分。

You can find some explanations about the difference between And and AndAlso on Whosebug.

给出的答案很好,但更好的方法是使用OfType预先过滤掉不需要的控件。这使得类型检查变得不必要。

For Each _CustomControl in Controls.OfType(Of CustomControl)
    If [criteria met]
        _CustomControl.CustomProperty = value
    End If
Next

如果您不想使用它,那么您需要在尝试访问 CustomProperty 之前转换为 CustomControl 类型,如下所示:

For Each _CustomControl As Control In Controls
    If TypeOf _CustomControl Is CustomControl And [criteria met]
        DirectCast(_CustomControl,CustomControl).CustomProperty = value
    End If
Next