Skip to content

Instantly share code, notes, and snippets.

@sunmeat
Created October 23, 2023 10:27
Show Gist options
  • Save sunmeat/feb3df9ba3dd40b3303eedd543f8c514 to your computer and use it in GitHub Desktop.
Save sunmeat/feb3df9ba3dd40b3303eedd543f8c514 to your computer and use it in GitHub Desktop.
read attribute by reflection
using System.Reflection;
[AttributeUsage(AttributeTargets.Property)]
public class MyAttribute : Attribute
{
public string Description { get; }
public MyAttribute(string description)
{
Description = description;
}
}
public class MyClass
{
[MyAttribute("Это описание свойства.")]
public int MyProperty { get; set; }
public static void Main()
{
Type type = typeof(MyClass); // Получаем тип класса
// Получаем информацию о свойстве
PropertyInfo propertyInfo = type.GetProperty("MyProperty");
// Проверяем, есть ли атрибут MyAttribute на свойстве
MyAttribute attribute = (MyAttribute)propertyInfo.GetCustomAttribute(typeof(MyAttribute));
if (attribute != null)
{
Console.WriteLine("Описание атрибута: " + attribute.Description);
}
else
{
Console.WriteLine("Атрибут MyAttribute не найден.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment