首页 > 解决方案 > 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;

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

标签: c#attributescontrols

解决方案


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

[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));
    }

推荐阅读