自定义Attribute例子!

==========================属性(Attribute就是一个标签)================
有很多也把它叫作特性(这样也好,可以和类的属性(Property)相区别!)
其它效果就是在指定的目标上面附加一点信息。
这些目标可以是:程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、
                可移植可执行文件模块、参数、属性 (Property)、返回值、结构或其他属性 (Attribute)。

MSDN是如下说明的:
公共语言运行库允许您添加类似关键字的描述性声明(称为属性 (Attribute))来批注编程元素,
如类型、字段、方法和属性 (Property)。
Attribute 类将预定义的系统信息或用户定义的自定义信息与目标元素相关联。
目标元素可以是程序集、类、构造函数、委托、枚举、事件、字段、接口、方法、
可移植可执行文件模块、参数、属性 (Property)、返回值、结构或其他属性 (Attribute)。

具体的步骤如下:
1)制作标签
2)贴标签

using  System;
using  System.Reflection;
using  System.Collections.Generic;
using  System.Text;

namespace  TestSpace
... {
    
//1)制作标签
    public class FriutTypeAttribute : Attribute
    
...{
        
public string Note
        
...{
            
get ...return "所有有苹果都我家种的!"; }
        }

    }


    [FriutType]         
//2)贴标签
    public class Apple
    
...{
        
private string _color;
        
public Apple(string color) ...{ _color = color; }
        
public string Color 
        
...{
            
get ...return _color; }
        }

    }


    
class DemoClass
    
...{
        
static void Main(string[] args)
        
...{
            Apple a 
= new Apple("红色");
            Console.WriteLine(
"苹果的颜色是:{0} ", a.Color);

            
//3)查看标签上的信息
            Type type = a.GetType();
            
foreach (Attribute attr in Attribute.GetCustomAttributes(type))
            
...{
                
if (attr.GetType() == typeof(FriutTypeAttribute))
                    Console.WriteLine(
"显示Apple的相关信息: {0}", ((FriutTypeAttribute)attr).Note);
            }

        }

    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值