2

我已经搜索了将近一个星期,但我似乎无法解决我的简单问题。我想获取项目中所有表单的所有名称和文本属性。

这是我的代码:

using System.Reflection;

Type Myforms = typeof(Form);
foreach (Type formtype in Assembly.GetExecutingAssembly().GetTypes())
{
    if (Myforms.IsAssignableFrom(formtype))
    {
      MessageBox.Show(formtype.Name.ToString()); // shows all name of form
      MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString()); // it shows null exception
    }
}

我需要将表单的名称和.Text表单存储在数据库中以控制用户权限。

4

3 回答 3

3

MessageBox.Show(formtype.GetProperty("Text").GetValue(type,null).ToString());显示异常,因为您需要一个实例Form来获取其Text属性,因为 Form 没有静态 Text 属性。

要获取默认 Text 属性,请创建一个实例

var frm = (Form)Activator.CreateInstance(formtype);
MessageBox.Show(formtype.GetProperty("Text").GetValue(frm, null).ToString());
于 2014-07-29T04:16:36.877 回答
1

要读取属性,您需要创建表单的新实例。在上面,您正在浏览从Form-class 继承的所有类型。您可以阅读不同的 Form-class 名称,仅此而已。

要阅读Text-property,您需要浏览Forms. 您可以使用Application.OpenForms来读取打开表单的TextName属性。

你可以试试这个来读取属性:

List<KeyValuePair<string, string>> formDetails = new List<KeyValuePair<string, string>>();
Type formType = typeof(Form);
foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
{
   if (formType.IsAssignableFrom(type))
   {
      using (var frm = (Form)Activator.CreateInstance(type))
      {
         formDetails.Add(new KeyValuePair<string, string>(frm.Name, frm.Text));
      }
   }
}

我修复了代码,它现在应该可以工作了。

于 2014-07-29T04:27:28.153 回答
1

属性.Text.Name不是静态的。因此,如果不调用该表单的构造函数,您将无法获取该属性的值。您必须创建该表单的对象才能读取该属性。

List<String> formList = new List<String>();
Assembly myAssembly = Assembly.GetExecutingAssembly();

foreach (Type t in myAssembly.GetTypes())
{
    if (t.BaseType == typeof(Form))
    {
        ConstructorInfo ctor = t.GetConstructor(Type.EmptyTypes);
        if (ctor != null)
        {
            Form f = (Form)ctor.Invoke(new object[] { });
            formList.Add("Text: " +  f.Text + ";Name: " + f.Name);
        }
    }
}
于 2014-07-29T04:32:25.960 回答