如何取得一个类的描述文本?
[Description( "日程安排 ")]
public partial class test : System.Web.UI.UserControl
怎样取得这个Description中的内容?
------解决方案--------------------用反射
------解决方案--------------------namespace attri
{
[AttributeUsage(AttributeTargets.Class)]
public class myAttribute : Attribute
{
private string name;
private string age;
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public string Age
{
set
{
age = value;
}
get
{
return age;
}
}
public myAttribute(string name)
{
this.name = name;
//
// TODO: 在此处添加构造函数逻辑
//
}
}
[attri.my( "hegang ",Age= "28 ")]
public class AttributeTest
{
public AttributeTest()
{
}
}
}
使用:
Type t = typeof(AttributeTest);
attri.myAttribute[] mt = (attri.myAttribute[])Attribute.GetCustomAttributes(t, typeof(attri.myAttribute));
Response.Write(mt[0].Name + " " + mt[0].Age);
------解决方案--------------------反射:http://hi.baidu.com/sanlng/blog/item/7202b758b83c4ede9c8204e6.html
特性:http://hi.baidu.com/sanlng/blog/item/9cd58c01aef593061c95832f.html
两篇基础的文章,希望对楼主有帮助
------解决方案--------------------Type t = typeof(test );
System.ComponentModel.DescriptionAttribute[] at =(System.ComponentModel.DescriptionAttribute[]) t.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
Response.Write(at[0].Description);
------解决方案--------------------use Reflection, for example:
using System;
using System.ComponentModel;
using System.Reflection;
class TestDesc
{
[Description( "Number ")]
public int Count
{
get {return _count;}
set {_count= value;}
}
int _count;
public static void Main()
{
Type t = typeof(TestDesc);
MemberInfo[] mis = t.GetMember( "Count ");
foreach (Attribute a in mis[0].GetCustomAttributes(typeof(DescriptionAttribute),false))
{
Console.WriteLine(((DescriptionAttribute)a).Description);
}
}
}