Обобщённый атрибут
Класс атрибута наследует Attribute и
объявляет параметр типа: InfoAttribute<T>.
На тип вешают [Info<int>] - так задают
аргумент обобщения. Прочитать его можно через
Attribute.GetCustomAttribute и
typeof помеченного класса.
Синтаксис
class InfoAttribute<T> : Attribute { }
[Info<int>]
class Worker { }
Пример
Давайте прочитаем атрибут и выведем имя типа аргумента:
using System;
class InfoAttribute<T> : Attribute
{
}
[Info<int>]
class Worker
{
}
class Program
{
static void Main()
{
var attr = Attribute.GetCustomAttribute(
typeof(Worker),
typeof(InfoAttribute<int>));
var typeName = attr.GetType().GenericTypeArguments[0].Name;
Console.WriteLine(typeName);
}
}
Результат выполнения кода:
"Int32"
Пример
Давайте повесим атрибут с типом string:
using System;
class InfoAttribute<T> : Attribute
{
}
[Info<string>]
class Row
{
}
class Program
{
static void Main()
{
var attr = Attribute.GetCustomAttribute(
typeof(Row),
typeof(InfoAttribute<string>));
var typeName = attr.GetType().GenericTypeArguments[0].Name;
Console.WriteLine(typeName);
}
}
Результат выполнения кода:
"String"
Пример
Давайте проверим наличие атрибута через typeof:
using System;
class InfoAttribute<T> : Attribute
{
}
[Info<int>]
class Token
{
}
class Program
{
static void Main()
{
bool has = Attribute.IsDefined(typeof(Token), typeof(InfoAttribute<int>));
Console.WriteLine(has);
}
}
Результат выполнения кода:
True
Смотрите также
-
параметр типа,
который объявляетTу класса -
открытый тип,
который описывает обобщение черезtypeof -
typeof,
который получаетTypeпо имени типа -
наследование,
которым атрибут наследуетAttribute