zoukankan      html  css  js  c++  java
  • 自定义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);
                }

            }

        }

    }
  • 相关阅读:
    APP-SERVICE-SDK:setStorageSync:fail;at page/near/pages/shops/shops page lifeCycleMethod onUnload function
    css 别人找的css特效
    项目笔记2
    Win7如何删除需要管理员权限才能删除的文件夹
    Win7下C:UsersCortana以账户名称命名的系统文件夹用户名的修改
    Win10下C:UsersJohn以账户名称命名的系统文件夹用户名的修改
    windows10企业版怎么关闭自动更新
    给MySQL_5.7 配置环境变量
    用PE安装操作系统时:无法创建新的系统分区 也无法定位现有系统分区 的解决办法
    电脑内存和磁盘空间有什么区别与联系
  • 原文地址:https://www.cnblogs.com/freebird92/p/605047.html
Copyright © 2011-2022 走看看