c# - 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));
}
推荐阅读
- javascript - Action for clicked marker on Google Map
- lodash - Rollupjs:忽略代码行
- tensorflow - Tensorflow 代码准确率没有提高
- css - Ionic 3 如何在自定义离子输入中垂直居中文本?
- javascript - 从匹配文本的位置获取值
- twilio - Twilio 可编程聊天消息数据
- c# - asp.net:如何通过特定行中的复选框更新 GridView 中的数据
- r - 使用 2 种不同颜色的线框绘图
- vba - 公式拖拽查询
- ibm-cloud - 尝试从 IBM Cloud 控制台供应 Analytics Engine 时出错:BXNIM0511E