.NET CORE 自定义特性的简单操作

小Z今天在玩.NET CORE的时候尝试进行自定义特性的编写,发现调用方法与.NET Framework 和早期的.NET CORE有差别。

.NET CORE 1.0 的参考书中的源代码为:

Attribute supportsAttribute = Attribute.GetCustomAttributes(assembly1,typeof(SupportsWhatsNewAttribute));

小Z发现API发生了改变,所以小Z尝试重新调试了一下代码,小Z新建了基于框架.NET CoreApp 1.1的控制台应用程序。

类分布:

1.自定义特性 TestAttribute.cs

using System;

namespace Demo.Domain.Utilities
{
    public class TestAttribute : Attribute
    {
        public Level Level { get; set; }

        public TestAttribute(Level level)
        {
            this.Level = level;
        }        
    }

    public enum Level
    {
        YES,
        NO,
    }

}

2.接口 Isay.cs

namespace TestConsoleApp
{
    public interface ISay
    {
        string Say();
    }
}


3.实现类 HelloSay.cs
using Demo.Domain.Utilities;

namespace TestConsoleApp
{
    [Test(Level.NO)]
    public class HelloSay : ISay
    {
        [Description("American")]
        public string Language { get; }

        public string Say()
        {
            return "Hello";
        }
    }
}


4.自定义特性测试类 ThePress.cs

using Demo.Domain.Utilities;
using System;
using System.Reflection;

namespace TestConsoleApp
{
    public class ThePress
    {
        public static void Print(ISay say)
        {
            var type = say.GetType();
            var typeInfo = type.GetTypeInfo();
            //判断是否存在特性
            if (typeInfo.IsDefined(typeof(TestAttribute)))
            {
                //从TypeInfo中获取特性
                var attr = typeInfo.GetCustomAttribute<TestAttribute>();
                if (attr.Level == Level.YES)
                {
                    Console.WriteLine("I can say " + say.Say());
                }
                else
                {
                    Console.WriteLine("I can not say " + say.Say());
                }
            }
            
            var props = type.GetProperties();
            foreach (var prop in props)
            {
                if (prop.IsDefined(typeof(DescriptionAttribute)))
                {
                   Console.WriteLine(prop.Name +":"+prop.GetCustomAttribute<DescriptionAttribute>().Language);
                }
            }
            
        }   
    }
}

5.控制台应用类 
using System;

namespace TestConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            ISay sayHello = new HelloSay();
            Console.WriteLine(sayHello.Say());
            ThePress.Print(sayHello);

            ISay sayHi = new HiSay();
            Console.WriteLine(sayHi.Say());
            ThePress.Print(sayHi);

            Console.ReadLine();
        }
    }
}

从代码中可以发现,现在要获取一个类的自定义特性,需要通过如下的方式:

var typeInfo = type.GetTypeInfo();

var attr = typeInfo.GetCustomAttribute<T>();



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值