c# winforms根据带有属性的字段Attributes关键字动态创建控件

问题描述

我有一个带字段的类;

bool field1;
bool field2;
bool field3;
...
bool field44;
bool field45;
...

我想用字段动态填充表单,但只能填充特定字段。 而不是使用“if”按名称解析字段, 是否可以在我希望包含在我的 UC 中的那些字段上设置一个属性,并仅显示那些。

[UC]//will be later on used to create a check Box
bool field1;
[NOT_UC] //will be ignored
bool field2;
[UC]//will be later on used to create a check Box
bool field3;

有没有其他更优雅的设计模式可以解决这个问题?

解决方法

没关系。 我想到了。 首先我创建了一个自定义属性:

[AttributeUsageAttribute(AttributeTargets.Field)]
public class UCAttribute : System.Attribute
{
    public UCAttribute()
    { }
}

并将 [UC] 属性设置为所需字段

[UC]
bool field1;

后来在加州大学:

    foreach (var prop in item.GetType().GetFields())
    {
        object[] attribute = prop.GetCustomAttributes(true);
        if (attribute.Length >= 1)
            Console.WriteLine("{0}={1} ",prop.Name,prop.GetValue(item));
    }