繁体   English   中英

从另一个类获取组件信息在C#中失败

[英]getting component info from another class fails in c#

我有一个带有按钮和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");
                    }
                }
            }
        }
    }

为什么它不起作用?

我已经访问了以下这些链接,但无法利用它们解决问题:

从另一个类 访问表单 组件从另一个类 访问表单控件 如何从c#中的另一个表单访问可视组件

谢谢

您要求输入错误的类型以提供答案。 相反,要求输入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代码中工作,因为从本质this.GetType()GetType()等效于this.GetType()就是表单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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