1.代码:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace TestProject1
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestAttributeMethod1()
{
//字段特性使用
var testClass = new TestClass();
//获取表特性
var getCustomAttributes = testClass.GetType().GetCustomAttributesData();
var attributeName = getCustomAttributes[0].AttributeType.Name;//特性名
var attributeValue = getCustomAttributes[0].ConstructorArguments[0].Value;//特性值
//获取整个类的特性值
var getAttributeNames = getAttributeNames<TestClass>();
// 获取指定属性的属性描述
var fieldIfno = typeof(TestClass).GetProperty("Id").GetCustomAttribute<Test2Attribute>();
}
/// <summary>
/// 获取设定类的Attribute的List
/// </summary>
/// <typeparam name="T">类</typeparam>
/// <returns></returns>
public List<string> getAttributeNames<T>()
{
List<string> resultList = new List<string>();
PropertyInfo[] pi = typeof(T).GetProperties();//获取类的全部属性信息
foreach (var item in pi)
{
//GetCustomAttributes返回的是一个object的数组
var obj = item.GetCustomAttributes(typeof(Test2Attribute), false);
if (obj != null)
{
//获取第一个特征,可能为空或者多个
var displayname = ((Test2Attribute)obj[0]).Name;
resultList.Add(displayname);
}
}
return resultList;
}
/// <summary>
/// 测试类
/// </summary>
[Test1("123456")]
public class TestClass
{
[Test2("123456",Name ="1111")]
public int Id { get; set; }
}
/// <summary>
/// 测试特征1
/// </summary>
public class Test1Attribute : Attribute
{
public Test1Attribute(string name)
{
}
}
/// <summary>
/// 测试特征2
/// </summary>
public class Test2Attribute : Attribute
{
public Test2Attribute(string name)
{
}
public string Name { get; set; }
}
}
}
2.应用
可以通过特征去生成指定的数据,比如根据特征,生成一个json,用于渲染UI的需要的,
或者根据生成的数据自动化完成,一个数据库管理系统,这样就不需要每个类都独立开发一个页面,只要类出来了,那么界面就出来了(通用界面)