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

            

                    

  • 相关阅读:
    JVM垃圾收集器-Parallel Scavenge收集器
    JVM垃圾收集器-ParNew收集器
    JVM垃圾收集器-Serial收集器
    UCloud数据盘扩容步骤
    java中强引用、软引用、弱引用、幻象引用有什么区别?分别使用在什么场景?
    java中exception和error有什么区别,运行时异常和一般异常有什么区别
    maven中的坐标和仓库
    Maven常用的构建命令
    Maven学习
    【设计原则和编程技巧】单一职责原则 (Single Responsibility Principle, SRP)
  • 原文地址:https://www.cnblogs.com/liangjie/p/2221957.html
Copyright © 2020-2023  润新知