在 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 中没有必需的项目。
RequiredMemberAttribute
。
bool isRequired = typeof(C1).GetProperty("P1").GetCustomAttribute<RequiredMemberAttribute>() != null;
这很容易发现使用 SharpLab。