1. 自定义attribute
[AttributeUsage(AttributeTargets.Method)] //标签适用范围
public class MyAttribute : Attribute
{
public string Message { get; set; }
public MyAttribute(string message)
{
Message = message;
}
}
2. 查找项目中所有使用了自定义标签的方法
public static IEnumerable GetMyAttributeMaked(List mappedKeys)
{
//项目中使用的所有dll
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
var neededAssemblies = new List();
foreach(var key in mappedKeys)
{
var searchedAssemblies = assemblies.Where(a => a.FullName.Contains(key));
if(searchedAssemblies != null && searchedAssemblies .Any())
{
neededAssemblies.AddRange(searchedAssemblies );
}
}
foreach (var assembly in neededAssemblies )
{
var filtedAttributes = assembly.GetTypes().Where(type => type.IsClass)
.SelectMany(m => m.GetMethods()).SelectMany(m => m.GetCustomAttributes(typeof(MyAttribute), false))
.Where(attribute => attribute is not null)
.Select(notNullAttribute => notNullAttribute as MyAttribute)
.ToList();
//do some work to customed attribute
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23