[英]getting component info from another class fails in c#
I have a winform with button and opendialog, here is my code : 我有一个带有按钮和opendialog的winform,这是我的代码:
[Form1.cs]: [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]: [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# 从另一个类 访问表单 组件从另一个类 访问表单控件 如何从c#中的另一个表单访问可视组件
thanks 谢谢
You are asking the wrong type to provide your answer. 您要求输入错误的类型以提供答案。 Instead, ask for the
frm.GetType()
: 相反,要求输入
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. 它可以在
Form
代码中工作,因为从本质this.GetType()
, GetType()
等效于this.GetType()
, 这就是表单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.