如何通过反射读取c# 11中的required属性

问题描述 投票: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 和 enum 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.