简体   繁体   English

使用反射从属性中获取

[英]Get From properties using reflection

I'm accessing form properties on this way:我以这种方式访问表单属性:

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;        

        }
    }
}

But each time when Form is accessed the Constructor is called and everything inside constructor is executed.但是每次访问 Form 时,都会调用构造函数并执行构造函数中的所有内容。 How to avoid this?如何避免这种情况?

If you want to get the names of the properties for that specific type, then you should just iterate through the types.如果您想获取该特定类型的属性名称,那么您应该只遍历这些类型。 There is a good example of that here 这里有一个很好的例子

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

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