C# 自定义特性例子

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

namespace ConsoleApp1
{

    [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method|AttributeTargets.Field,
        AllowMultiple =true,
        Inherited =true)]
    public class LastModifiedAttribute : Attribute
    {
        private readonly DateTime _dateModified;
        private readonly string _change;

        public LastModifiedAttribute(string dateModified, string change)
        {
            this._dateModified = DateTime.Parse(dateModified);
            this._change = change;
        }

        public DateTime DateModified => _dateModified;
        public string Change => _change;
        public string Issue { get; set; }  //可选参数

    }


    [AttributeUsage(AttributeTargets.Assembly)]
    public class SupportsWhatsNewAttribute : Attribute        //用于标记程序集 使用时 [assembly:SupportsWhatsNew]
    { 
    
    }




    [LastModified("2019-01-01","some change happened",Issue ="W")]
    class Program
    {

        [LastModified("2019-01-01", "some change happened", Issue = "W")]
        [LastModified("2019-01-03", "some other happened")]
        static void Main(string[] args)
        {
        }
    }


    
}
发布了12 篇原创文章 · 获赞 0 · 访问量 1657

猜你喜欢

转载自blog.csdn.net/zxcvb036/article/details/104110751