木子屋 Dnawo's BLOG

C#特性(Attribute)示例

👤 dnawo 📅 2010-01-23 👁 4897 👍 0 💬 0 🔄 来源:本站原创
[AttributeUsage(AttributeTargets.All,Inherited=false)]
public class TestAttribute : System.Attribute
{
	//Fields
	private string _description;
	
	//Properties
	public string Description
	{
		get { return _description; }
	}
	
	//Constructor
	public TestAttribute(string description)
	{
		this._description = description;
	}
}

[Test("user-defined class")]
public class TestClass
{
	//Constructor
	public TestClass()
	{}
	
	//Methods
	[Test("user-defined method")]
	public int Add(int a, int b)
	{
		return a + b;
	}
}

调用示例:

using System;
using System.Reflection;

namespace Console_Application
{
	class Program
	{
		public static void Main(string[] args)
		{
			Type t = typeof(TestClass);
			MemberInfo memberInfo = t;
			TestAttribute attribute = (TestAttribute)Attribute.GetCustomAttribute(memberInfo,typeof(TestAttribute));
			Console.WriteLine(attribute.Description);
			
			MethodInfo methodInfo = t.GetMethod("Add");
			TestAttribute attribute2 = (TestAttribute)Attribute.GetCustomAttribute(methodInfo,typeof(TestAttribute));
			Console.WriteLine(attribute2.Description);
			
			Console.ReadKey(true);
		}
	}
}

评论(0)

暂无评论。

计算题
评论需审核通过后显示
← 上一篇 SP点播/定购指令与代码必须采用精确匹配方式(双精) 下一篇 → 服装号型表示方法及说明