簡體   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