C#中Attribute的用法

Attribute的一些用法

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

namespace ConsoleApp32
{
    class MyCustomAttribute : Attribute
    {
        public string info;

        public MyCustomAttribute(string info)
        {
            this.info = info;
        }

        public void TestFun()
        {
            Console.WriteLine("特性的方法");
        }
    }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = true)]
    public class MyCustom2Attribute : Attribute
    {
       

    }

    class TestClass
    {
        [Obsolete("OldSpeak方法已经过时了,请使用Speak方法",false)]
        public void OldSpeak(string str)
        {
            Console.WriteLine(str);
        }

        public void Speak()
        {

        }

        public void SpeakCaller(string str,[CallerFilePath]string fileName=" ",[CallerLineNumber]int line=0,[CallerMemberName]string target="")
        {

        }
    }



    [MyCustom("这个是我自己写的一个类")]
    class MyClass
    {
        [MyCustom("这是一个成员变量")]
        public int value;

        [MyCustom("这是一个用于计算假发的函数")]
        public void TestFun([MyCustom("函数参数")]int a)
        {
            Console.WriteLine();
        }
    }

    class Program
    {

        static void Fun()
        {
            Console.WriteLine("Fun执行");
        }

        static void Main(string[] args)
        {
            // MyClass mc = new MyClass();
            // Type t = mc.GetType();
            // if(t.IsDefined(typeof(MyCustomAttribute),false))
            // {
            //     Console.WriteLine("该类型应用了MyCustom特性");
            // }

            //object[] array= t.GetCustomAttributes(true);
            // for(int i=0;i<array.Length;i++)
            // {
            //     if(array[i] is MyCustomAttribute)
            //     {
            //         Console.WriteLine((array[i] as MyCustomAttribute).info);
            //         (array[i] as MyCustomAttribute).TestFun();
            //     }
            // }

            

        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值