欢迎光临

木子屋

标题: C#特性(Attribute)示例

作者: dnawo

日期: 2010-01-23 12:20 AM

分类: Web编程

内容: 复制内容到剪贴板 程序代码[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)

登录

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.769 ms

返回

标题: C#特性(Attribute)示例

你没有权限发表评论

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.769 ms

返回

暂无评论

返回

────────────

木子屋

PJBlog3 v3.2.9.518 Inside.

Processed In 0.815 ms

返回