简体   繁体   中英

getting component info from another class fails in c#

I have a winform with button and opendialog, here is my code :

[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");
                    }
                }
            }
        }
    }

why it does not work ?

I have visited these links below but I could not utilize them to solve my problem :

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

thanks

You are asking the wrong type to provide your answer. Instead, ask for the 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;
}

It worked in the Form code because inherently, GetType() is equivalent to this.GetType() , with this being the form.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM