如何通过反射读取C# 11中所需的属性

问题描述 投票:0回答:1

在 C# 11 中,微软引入了字段和属性所需的属性作为类的成员。 我需要在反射中读取这个属性。我该怎么做? 例如,在类 C1 和属性 P1 中,我们需要读取必需的属性。

   class C1
   {
     public int required P1 { get; set; }

   }
   .
   ..
   Type targetType = typeof(C1);
   PropertyInfo propertyInfo = targetType.GetProperty("P1");
   propertyInfo.?????

propertyInfo.Attributes 和枚举 System.Reflection.TypeAttributes 没有必需的项目。

c# reflection properties required
1个回答
0
投票

所需成员饰有

RequiredMemberAttribute

bool isRequired = typeof(C1).GetProperty("P1").GetCustomAttribute<RequiredMemberAttribute>() != null;

这很容易发现使用 SharpLab

© www.soinside.com 2019 - 2024. All rights reserved.