zoukankan      html  css  js  c++  java
  • 自定义Attribute(原创) 中庸

        一.理论

                     Attribute在msdn中被翻译成属性,我感觉不太适合.我更赞成前辈王涛(<你必须知道的.net>的作者)对之的称呼--特性.

              看过王涛前辈的书,记得王涛前辈对特性做过这样的描述:   特性attribute,本质上是一个类,其为目标元素提供关联附加信息,

             并在运行期以反射的方式来获取附加信息.感觉不太全面.但目前还没有太多时间找相关的资料,所以姑且先这样认为.

       二.示例

                0.示例方案图

                    

                1.自定义Attribute(DefaultAttribute.cs)

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace TestAttribute
    {
        public class DefaultAttribute:Attribute
        {
            public string DefaultName { get; set; }
        }
    }

     

               2.使用自定义的Attribute (Model.cs)        

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace TestAttribute
    {
        public  class Model
        {
            [Default(DefaultName="姓名")]
            public String name { get; set; }
       
            [Default(DefaultName="成绩")]
            public Byte Score { get; set; }
        }
    }

              3.测试按钮代码(如下)          

                String modelpropertiesattributes ="";
                Type t = typeof(Model);
                PropertyInfo[] pis = t.GetProperties();
                foreach (PropertyInfo pi in pis)
                {
                    modelpropertiesattributes+=((DefaultAttribute)pi.GetCustomAttributes(true)[0]).DefaultName+":";
                }
                modelpropertiesattributes=modelpropertiesattributes.Substring(0, modelpropertiesattributes.Length-1);
                MessageBox.Show(modelpropertiesattributes);

       4.测试结果(如下图)

            

                    

  • 相关阅读:
    writeToFile 读写文件问题
    iOS 设置代理过程
    iOS UIView 快速修改 frame,
    touches,motion触摸事件响应
    集合视图控制器(CollectionViewController) 、 标签控制器(TabBarController) 、 高级控件介绍
    触控(Touch) 、 布局(Layout)
    Autoresizing和AutoLayout
    动画(Animation) 、 高级动画(Core Animation)
    ios开发环境 分支语句 、 循环结构(for) 、 循环结构
    oc内存管理总结(一)
  • 原文地址:https://www.cnblogs.com/liangjie/p/2221957.html
Copyright © 2011-2022 走看看