CustomButton类中img变量是否冗余?点击效果异常咨询
当前代码可正常运行,但存在疑问:CustomButton类中已定义_originalImage变量,img变量是否属于冗余?移除img后,按钮点击时颜色会持续变暗且无法恢复至原色。
当前类成员与构造函数代码
private bool _DisplayFocusCues = true; private Image _originalImage; private Image _clickImage; private Image img; public CustomButton() { this.FlatStyle = FlatStyle.Flat; this.FlatAppearance.BorderSize = 0; this.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); // Transparent this.FlatAppearance.MouseDownBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on click this.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on hover this.DisplayFocusCues = false; // Assume Properties.Resources.YourImageResource is the resource identifier for your image img = ResizeImage(Properties.Resources.icons8_record_32, 50, 50); this.Image = img; this.Size = img.Size; _originalImage = img; }
OnMouseUp事件代码
protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); _originalImage = img; this.Image = _originalImage; }
核心原因:img是未被修改的原始图像副本
img变量并非冗余,问题本质是Image是引用类型:
- 当你在按钮点击的逻辑(未贴出的代码)中修改按钮的图像颜色时,实际上是直接修改了当前
this.Image指向的Image实例的像素数据。如果只保留_originalImage,它和this.Image指向的是同一个对象,修改后_originalImage的内容也会被污染,导致无法恢复原始状态。 img保存的是初始缩放完成后未被修改的干净Image实例,无论你怎么修改按钮当前显示的图像,img始终是最初的原始版本。所以在OnMouseUp时重新将this.Image指向img,才能让按钮恢复原色。
当前代码里的_originalImage才是真正的冗余——它只是重复引用了img,完全可以去掉。
优化方案(移除冗余变量)
- 删除类成员中的
_originalImage变量 - 构造函数简化为:
private bool _DisplayFocusCues = true; private Image _clickImage; private Image img; public CustomButton() { this.FlatStyle = FlatStyle.Flat; this.FlatAppearance.BorderSize = 0; this.FlatAppearance.BorderColor = Color.FromArgb(0, 255, 255, 255); // Transparent this.FlatAppearance.MouseDownBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on click this.FlatAppearance.MouseOverBackColor = Color.FromArgb(0, 255, 255, 255); // Transparent on hover this.DisplayFocusCues = false; img = ResizeImage(Properties.Resources.icons8_record_32, 50, 50); this.Image = img; this.Size = img.Size; }
- OnMouseUp事件简化为:
protected override void OnMouseUp(MouseEventArgs mevent) { base.OnMouseUp(mevent); this.Image = img; }
这样既保留了按钮点击恢复原色的功能,又消除了冗余的变量引用。
内容的提问来源于stack exchange,提问作者Daniel Lip
相关产品推荐
相关产品推荐

