foreach (var p in this.components.Components)
            {
               try{
      Component comp =p as Component ;
MessageBox.Show(comp.GetType().Name);
                    }
            }    

解决方案 »

  1.   


    private void button1_Click(object sender, EventArgs e)
            {            foreach (var p in this.components.Components)
                {
                    try
                    {
                        Component comp = p as Component;
                        MessageBox.Show(comp.GetType().Name);
                    }
                    catch (System.Exception abc)
                    {
                        MessageBox.Show(abc.Message);
                    }
                }       
            }用你的方法,还是不行
      

  2.   

    要么是你的 this.components为null
    要么是 this.components.Components 为null···
      

  3.   

    private void button1_Click(object sender, EventArgs e)
            {
           if (this.components != null && this.components.Components != null){
              foreach (Component comp in this.components.Components)
                {
                    if (comp != null)
                    {
                        MessageBox.Show(comp.GetType().Name);
                    }
                }     
            }
    }
      

  4.   

    呵呵,我也在找原因,我觉得1楼这种写法,不应该有问题,为什么存在NULL 问题呢,既然是组件,应该都是存在的啊,不应该NULL啊
      

  5.   

    this.components是组件的容器,如果你的窗体没有组件,components一直保持为null。
    窗体有没有组件简单的判断方法:找到相应Designer.cs,在里面搜components,如果只能搜到两处,表明你的窗体没有组件。Button、Label、TextBox不是组件
    Timer是组件也就是:他是管理组件的一个容器。
      

  6.   

    呵呵,我也在找原因,我觉得1楼这种写法,不应该有问题,为什么存在NULL 问题呢,既然是组件,应该都是存在的啊,不应该NULL啊如果没有组件,components属性值为 null。所以你需要先判断一下是不是 null。不是说什么要“try....catch”。这种方式就是“只找解决办法却不思考原因。(其实是只找糊弄办法,而不是真正解决办法)你的代码的逻辑应该这样设计
    if( this.components== null)
             MessageBox.Show(”木有主见!"));
    else
    {
             foreach (Component comp in this.components.Components)
                {
                      MessageBox.Show(comp.GetType().Name);
               }   
    }
      

  7.   

    呵呵,我也在找原因,我觉得1楼这种写法,不应该有问题,为什么存在NULL 问题呢,既然是组件,应该都是存在的啊,不应该NULL啊如果没有组件,components属性值为 null。所以你需要先判断一下是不是 null。不是说什么要“try....catch”。这种方式就是“只找解决办法却不思考原因。(其实是只找糊弄办法,而不是真正解决办法)你的代码的逻辑应该这样设计
    if( this.components== null)
             MessageBox.Show(”木有主见!"));
    else
    {
             foreach (Component comp in this.components.Components)
                {
                      MessageBox.Show(comp.GetType().Name);
               }   
    }恩,谢谢大家,我对C#里面的一些概念还不是太清楚,所以就闹出来这些问题,谢谢
      

  8.   


    用你这种方法,循环一个都没进入,郁闷郁闷?我只能呵呵了撒···
    这说明 为 null撒··
    有啥郁闷的···
    我去···
      

  9.   


    用你这种方法,循环一个都没进入,郁闷
    没有components,有什么郁闷的?