foreach 的自动转化类型

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


        
private void Form1_Load(object sender, EventArgs e)
        
{
            
object[] persons = new object[3];
            persons[
0]=(new Person("x"));
            persons[
1= (new Person("y"));
            persons[
2= (new Person("z"));

            
//从persons中取出的成员是object类,foreach会自动将其转化为目标类型
            foreach (Person person in persons)
            
{
                MessageBox.Show(person.Name);
            }
 
        }

    }


    
public class Person
    
{
        
public string Name;

        
public Person( string n)
        
{
            
this.Name = n;
        }

    }

}

posted on 2007-12-05 16:55  shcity  阅读(363)  评论(0编辑  收藏  举报

导航