WinForm中访问LedIndicator控件自定义属性遇CS1061错误求助
解决TA.Winforms.Controls.LedIndicator自定义属性访问问题
问题根源:this.Controls集合返回的是Control基类对象,即便实际实例是LedIndicator,编译器也只会识别Control的通用属性。Cadence是LedIndicator的自定义属性,基类Control没有定义,所以必须将对象转换为LedIndicator类型才能访问。
两种可行解决方法
1. 强制类型转换
直接将Controls返回的对象强制转换为LedIndicator类型:
var ld1 = (TA.Winforms.Controls.LedIndicator)this.Controls[Global.ldcNames[rowNum]]; ld1.Cadence = CadencePattern.SteadyOn;
注意:如果控件不存在或类型不匹配,这种方式会抛出
InvalidCastException或NullReferenceException。
2. 使用as运算符安全转换
as运算符会在转换失败时返回null,可以提前判断避免异常:
var ld1 = this.Controls[Global.ldcNames[rowNum]] as TA.Winforms.Controls.LedIndicator; if (ld1 != null) { ld1.Cadence = CadencePattern.SteadyOn; }
为什么之前的Label可以直接访问?
因为Text是Control基类自带的属性,所有WinForm控件都继承了这个属性,所以无需转换就能访问。而Cadence是LedIndicator特有的自定义属性,不属于基类Control的成员,必须转换到具体子类才能调用。
内容的提问来源于stack exchange,提问作者Steven Sheeley
相关产品推荐
相关产品推荐

