欢迎来到.net学习网

欢迎联系站长一起更新本网站!QQ:879621940

您当前所在位置:首页 » ASP.Net » 正文

热门阅读

Asp.net中如何查找类属性的自定义Attribute

创建时间:2014年04月23日 16:35  阅读次数:(12573)
分享到:

经常我们需要为类的属性增加一些自定义的标签(Attribute),那么为属性应用了自定义的标签后,我们要如何查到这些自定义标签呢?下面是一个小示例:

1,我们先定义一个自定标签:

[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute : Attribute
{
   public string DescriptionContent
   {
       get;
       set;
   }

   public DescriptionAttribute(string _descriptioncontent)
   {
       this.DescriptionContent = _descriptioncontent;
   }
}

2,然后我们在某个类中应用该标签:
public enum eSourceType
{
   [DescriptionAttribute("物料类型")]
   Storage_Goods_Sort,
}

3,接下来我们可以这样取到上面Storage_Goods_Sort的DescriptionAttribute的值。
Type type = typeof(eSourceType);
MemberInfo memberInfo = type.GetMember("Storage_Goods_Sort ");
if (memberInfo.IsDefined(typeof(DescriptionAttribute), false))
{
   object[] Attributes = memberInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
   DescriptionAttribute descriptionAttribute = (DescriptionAttribute)Attributes[0];
   Console.WriteLine(descriptionAttribute.DescriptionContent);
}

注意,这里是使用枚举eSourceType来做的例子,如果将eSourceType改为一个类,读取自定义标签的方法也是一样的。只不过是将MemberInfo memberInfo = type.GetMember("Storage_Goods_Sort");改为MethodInfo methodInfo = type.GetMethod("Storage_Goods_Sort")即可。

来源:.net学习网
说明:所有来源为 .net学习网的文章均为原创,如有转载,请在转载处标注本页地址,谢谢!
【编辑:Wyf

打赏

取消

感谢您的支持,我会做的更好!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

最新评论

共有评论0条
  • 暂无任何评论,请留下您对本文章的看法,共同参入讨论!
发表评论:
留言人:
内  容:
请输入问题 78+81=? 的结果(结果是:159)
结  果: