自定义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);
            }

        }

    }

}
原文地址:https://www.cnblogs.com/freebird92/p/605047.html