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

            }

        }

    }
  • 相关阅读:
    new Array()和 = [] 二种初始化数组的性能比较
    指定 Flash Player 在加载对象前是否应检查跨域策略文件是否存在
    FLEXRangeError: Error #2006: 提供的索引超出范围
    把RSS订阅到邮箱去
    使用特殊效果创建一个堆叠纸张对登录表单
    30个特别的涂鸦和壁画
    12个免费的从文本到语音转换 的在线服务和工具
    40个创意的IPhone壁纸大集合,做应用程序必备
    如何防止 yum 自动更新
    VirtualBox 与 宿主机剪贴板共享问题
  • 原文地址:https://www.cnblogs.com/freebird92/p/605047.html
Copyright © 2020-2023  润新知