从c#中获取组件信息失败

时间:2016-05-25 10:18:54

标签: c# winforms

我有一个带按钮和opendialog的winform,这是我的代码:

[Form1.cs中]:

    using System;
    using System.Windows.Forms;

    namespace WindowsFormsApplication4
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                Class1 obj=new Class1();
                obj.get_info(this);
            }
        }
    }

[class1.cs]:

    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Linq;
    using System.Reflection;
    using System.Windows.Forms;

    namespace WindowsFormsApplication4
    {
        class Class1
        {

            private IEnumerable<Component> EnumerateComponents(Form frm)
            {
                return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
                       where typeof(Component).IsAssignableFrom(field.FieldType)
                       let component = (Component)field.GetValue(frm)
                       where component != null
                       select component;
            }

            public void get_info(Form frm)
            {
                foreach (Component c in EnumerateComponents(frm))
                {
                    if (c.GetType() == typeof(OpenFileDialog))
                    {
                        MessageBox.Show("Detected OpenFileDialog");
                    }
                }
            }
        }
    }

为什么它不起作用?

我已经访问过以下链接,但我无法利用它们来解决我的问题:

Access form component from another class Accessing Form's Controls from another class How to access a visual component from another form in c#

感谢

1 个答案:

答案 0 :(得分:0)

您提出错误的类型来提供答案。相反,请求frm.GetType()

private IEnumerable<Component> EnumerateComponents(Form frm)
{
    return from field in frm.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
        where typeof(Component).IsAssignableFrom(field.FieldType)
        let component = (Component)field.GetValue(frm)
        where component != null
        select component;
}

它适用于Form代码,因为从本质上讲,GetType()相当于this.GetType()就是形式。