.net 特性 反射 实例

本文介绍了一个.NET自定义特性的实现案例,包括特性定义、使用及通过反射获取特性信息的方法。展示了如何利用特性进行元数据存储,并在运行时通过反射读取这些信息。

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

代码如下,说明在注释里面。


using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace wlf.net { //定制特性也可以应用到其它定制特性上, //应用AttributeUsage,来控制如何应用新定义的特性。 [AttributeUsage(AttributeTargets.All,//可应用所有元素 AllowMultiple = true,//允许应用多次 Inherited = false)]//不继承到派生类 //特性也是一个类 //必须集成System.Attribute类。 //命名规范为:"类名"+Attribute. public class MySelfAttribute : Attribute { //定义字段 private string _name; private int _age; private string _memo; //必须定义构造函数,如果不定义有编译器提供的无参默认构造函数 public MySelfAttribute() { } public MySelfAttribute(string name, int age) { _name = name; _age = age; } //定义属性 //显然特性和属性不是一回事儿 public string Name { get { return _name == null ? string.Empty : _name; } } public int Age { get { return _age; } } public string Memo { get { return _memo; } set { _memo = value; } } //定义方法 public void ShowName() { Console.WriteLine("Hello ,{0}", _name == null ? "world." : _name); } } //应用自定义特性 //可以以MySelf或者MySelfAttribute作为特性名 //可以给属性Memo 赋值 [MySelf("wlf", 21, Memo = "wlf is My self.")] public class Mytest { public void SayHello() { Console.WriteLine("Hello,my.net world."); } } public class MyRun { public static void Main(String[] args) { //如何以反射确定特性信息 Type tp = typeof(Mytest); MemberInfo info = tp; MySelfAttribute myAttribute = (MySelfAttribute)Attribute.GetCustomAttribute(info, typeof(MySelfAttribute)); if (myAttribute != null) { //嘿嘿,在运行是查看注释内容,是不是很爽啊。 Console.WriteLine("Name:{0}", myAttribute.Name); Console.WriteLine("Age:{0}", myAttribute.Age); Console.WriteLine("Memo of {0} is {1}", myAttribute.Name, myAttribute.Memo); myAttribute.ShowName(); //多点反射 object obj = Activator.CreateInstance(typeof(Mytest)); MethodInfo mi = tp.GetMethod("SayHello"); mi.Invoke(obj, null); Console.Read(); } } } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值