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.测试结果(如下图)

            

                    

  • 相关阅读:
    Springmvc数据验证
    Springmvc文件上传
    BaseController
    说说NSProxy
    Objective-C的动态设计
    UITableView卡片式分组
    RunLoop应用之性能优化
    OC与JS交互之JavaScriptCore
    Core Data 迁移
    一个广告轮播视图的实现
  • 原文地址:https://www.cnblogs.com/liangjie/p/2221957.html
Copyright © 2011-2022 走看看