[英]c# winforms dynamically create controls based on fields with attributes (Attributes key word)
我有一个带有字段的 class;
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.