小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();
}
}
using Demo.Domain.Utilities;
namespace TestConsoleApp
{
[Test(Level.NO)]
public class HelloSay : ISay
{
[Description("American")]
public string Language { get; }
public string Say()
{
return "Hello";
}
}
}
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>();