Created
October 23, 2023 10:27
-
-
Save sunmeat/feb3df9ba3dd40b3303eedd543f8c514 to your computer and use it in GitHub Desktop.
read attribute by reflection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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