Метод GetCustomAttributes
Для метода удобно взять
MethodInfo и вызвать
GetCustomAttributes
или GetCustomAttribute.
У устаревшего метода читают
ObsoleteAttribute.Message.
Синтаксис
object[] attrs = member.GetCustomAttributes(typeof(ObsoleteAttribute), false);
Пример
Давайте прочитать Message
у метода с Obsolete:
using System;
using System.Reflection;
class Gate
{
[Obsolete("abcde")]
public void Run()
{
}
}
class Program
{
static void Main()
{
MethodInfo method = typeof(Gate).GetMethod("Run");
ObsoleteAttribute item = (ObsoleteAttribute)method
.GetCustomAttributes(typeof(ObsoleteAttribute), false)[0];
string res = item.Message;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте проверить число атрибутов на методе:
using System;
using System.Reflection;
class Gate
{
[Obsolete("abcde")]
public void Run()
{
}
}
class Program
{
static void Main()
{
MethodInfo method = typeof(Gate).GetMethod("Run");
int res = method.GetCustomAttributes(typeof(ObsoleteAttribute), false).Length;
Console.WriteLine(res);
}
}
Результат выполнения кода:
1
Пример
Давайте прочитать атрибут через
GetCustomAttribute:
using System;
using System.Reflection;
class Gate
{
[Obsolete("abcde")]
public void Run()
{
}
}
class Program
{
static void Main()
{
MethodInfo method = typeof(Gate).GetMethod("Run");
ObsoleteAttribute item = method.GetCustomAttribute<ObsoleteAttribute>();
string res = item.Message;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Смотрите также
-
MethodInfo,
описание метода -
GetMethods,
поиск метода -
PropertyInfo,
свойство -
BindingFlags,
флаги поиска