论坛首页 编程语言技术论坛

类属性的自定义

浏览 1333 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2015-10-21  
这里是使用枚举eSourceType来做的例子,如果将eSourceType改为一个类,读取自定义标签的方法也是一样的。只不过是将MemberInfo memberInfo = type.GetMember("Storage_Goods_Sort");改为MethodInfo methodInfo = type.GetMethod("Storage_Goods_Sort")即可。

我们先定义一个自定标签:
[AttributeUsage(AttributeTargets.All)]
public class DescriptionAttribute : Attribute
{
   public string DescriptionContent
   {
       get;
       set;
   }

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

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

接下来我们可以这样取到上面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);
}

开发者学习交流:http://www.yuantuan.com/index/index/edu
论坛首页 编程语言技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics