首页 > 解决方案 > 使用反射从属性中获取

问题描述

我以这种方式访问​​表单属性:

System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetEntryAssembly();
Type[] Types = myAssembly.GetTypes();
foreach (Type myType in Types)
{
    if (myType.BaseType == null) continue;
    
    if (myType.BaseType == typeof(Form))
    {                    
        var emptyCtor = myType.GetConstructor(Type.EmptyTypes);
        if (emptyCtor != null)                    
        {
            var f = (Form)emptyCtor.Invoke(new object[] { });
            string FormText = f.Text;
            string FormName = f.Name;
            string btype = myType.BaseType.FullName;        

        }
    }
}

但是每次访问 Form 时,都会调用构造函数并执行构造函数中的所有内容。如何避免这种情况?

标签: c#winformsreflection

解决方案


如果您想获取该特定类型的属性名称,那么您应该只遍历这些类型。这里有一个很好的例子


推荐阅读