自定义属性。
1、首先定义自定义属性:
public class DbAttribute : Attribute
{
/// <summary>
/// 是否自动加载数据
/// </summary>
public bool autoLoad = true;
}
2:类中引用自定义属性:
public class data节点 : iPublic.Model.__basic
{
public string aaa= "";
//不自动加载
[iPublic.Model.__basic.DbAttribute(autoLoad = false)]
public List<ccc> bbb = new List<ccc>();
}
3、反射读取自定义属性:
private object getCustomAttribute(MemberInfo member, Type attributeType, bool inherit)
{ //获取自定义属性
object[] objs = member.GetCustomAttributes(attributeType, inherit);
if (objs == null || objs.Length < 1) return null;
return objs[0];
}
//读取、使用
System.Reflection.FieldInfo f = GetType().GetField(sField);
DbAttribute att = getCustomAttribute(f, typeof(DbAttribute), true) as DbAttribute;
if (att != null && !att.autoLoad) continue; //不自动加载
原创,转载请注明海宏软件。
本文介绍了如何在C#中定义和使用自定义属性,通过`DbAttribute`类展示了如何创建一个用于标记是否自动加载数据的属性。然后在`data节点`类中应用该属性,设置`bbb`字段不自动加载。最后,通过反射方法`getCustomAttribute`读取并检查字段上的自定义属性,实现对自动加载行为的控制。这提供了一种灵活的方式来控制类成员的行为。
55

被折叠的 条评论
为什么被折叠?



