var c = new Test { Prop1 = "Hello" };
object? v = /*Нужно получить значение свойства c.Prop1, т.к. в интерфейсе оно помечено атрибутом [Test]*/ ;
[AttributeUsage(AttributeTargets.Property)]
internal sealed class TestAttribute : Attribute {}
internal interface ITest {
[Test]
string Prop1 { get; set; }
}
internal sealed class Test : ITest {
internal string Prop1 { get; set; }
}
using System.Reflection;
namespace ConsoleAppTest
{
public static class Program
{
private static void Main(string[] args)
{
Test obj = new() { Prop1 = "Prop1 Value" };
// Получаем тип объекта
Type objType = typeof(Test);
// Получаем список интерфейсов
Type[] interfaces = objType.GetInterfaces();
foreach (Type iface in interfaces)
{
// Получаем список свойств интерфейса
PropertyInfo[] ifaceProperties = iface.GetProperties();
foreach (PropertyInfo prop in ifaceProperties)
{
// Ищем нужный аттрибут в свойстве
Attribute? attribute = prop.GetCustomAttribute<TestAttribute>();
if (attribute != null)
{
// Получаем значение свойства
object? propValue = prop.GetValue(obj); // -> Prop1 Value
}
}
}
}
}
[AttributeUsage(AttributeTargets.Property)]
public sealed class TestAttribute : Attribute
{ }
internal sealed class Test : ITest
{
public string Prop1 { get; set; } = string.Empty;
}
internal interface ITest
{
[Test]
public string Prop1 { get; set; }
}
}