【转】c#自定义属性的示例

本文介绍了.NET中的自定义属性概念,通过实例演示了如何使用自定义属性来标记类或方法,并展示了如何通过反射技术读取这些自定义属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是自定义属性呢?
用过Web Service的人都会知道这样一个标记[WebMethod]
在方法,属性,类,结构等的前面加上形如“[xxx]”的标记,就可能用C#的反射技术读取这个标记。
其中xxx是继承自System.Attribute的类

由此可见,自定义属性可以用来标记某个类或方法是否具有某种属性,典型的应用就是[Serializable],[WebMethod]。

好的,来看一段代码:
[code]
using System;
using System.Reflection;
class Program
{
static void Main()
{
System.Attribute[] attrs = Attribute.GetCustomAttributes(typeof(xxx));
foreach (System.Attribute attr in attrs)
{
if (attr is aaa)
{
aaa a = (aaa)attr;
Console.WriteLine("name={0},version={1}",a.Name,a.Version);
}
}
}
}
[aaa("nid",Version=1)]
public class xxx
{
//...
}
public class aaa : Attribute
{
public aaa(string name)
{
this.name = name;
}
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private int version;
public int Version
{
get { return version; }
set { version = value; }
}
}[/code]

来自:http://www.ljnid.cn/?id=270

转载于:https://www.cnblogs.com/sk-net/archive/2009/12/31/1636811.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值