您的位置:首页 > 其它

关于对象引用的一个例子

2006-03-15 14:12 661 查看
关于对象引用的一个例子

关于对象引用的一个例子.注意不要和对象名字符串相混淆.
前提:假设有n个checkBox控件.验证checkBox 是否被选择.用for来实现.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections; //自己添加上去的.因为要用到里面的ArrayList类

namespace autorun
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
ArrayList checkboxArray=new ArrayList();
checkboxArray.Add(checkBox1); //此处添加的是控件引用而不是字符串
checkboxArray.Add(checkBox2);
checkboxArray.Add(checkBox3);
checkboxArray.Add(checkBox4);
checkboxArray.Add(checkBox5);
checkboxArray.Add(checkBox6);
checkboxArray.Add(checkBox7);
checkboxArray.Add(checkBox8);
checkboxArray.Add(checkBox9);
checkboxArray.Add(checkBox10);
for(int i=0;i {
CheckBox checkBoxTest = (CheckBox)checkboxArray[i]; //提取时一定要进行强制类型转换
if (checkBoxTest.Checked == true)
{
........
}
}
}
}
}

若从组表中提取对象时不进行类型转换会出现如下错误:
Cannot implicitly convert type 'object' to 'System.Windows.Forms.CheckBox'. An explicit conversion exists (are you missing a cast?)

特别感谢 CSDN ID:3000sunqin(3000suqnin)

JasonHeung(拥有一切不过就这样笑着哭)仁兄给出的另一种方法.目前尚未调试通过

for (int i = 0; i < this.Controls.Length; i++)
{
if (this.Controls[i].GetType() = typeof(CheckBox) && ((CheckBox)this.Controls[i]).Checked = true)
{
..............
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: