从记录中获取属性



我正在寻找一种方法来获得在记录构造函数上定义的属性"字段";。

// See https://aka.ms/new-console-template for more information
using System.ComponentModel.DataAnnotations;
var property = typeof(TestRecord)
.GetProperties()
.First( x => x.Name == nameof(TestRecord.FirstName) );
var attr0 = property.Attributes; // NONE
var attr1 = property.GetCustomAttributes( typeof(DisplayAttribute), true ); // empty
var property1 = typeof(TestRecord)
.GetProperties()
.First( x => x.Name == nameof(TestRecord.LastName) );
var attr2 = property1.Attributes; // NONE
var attr3 = property1.GetCustomAttributes( typeof(DisplayAttribute), true ); // Works
public sealed record TestRecord( [Display] String FirstName, [property: Display] String LastName );

我可以在LastName上获取针对该属性的属性(使用property:(。

但是我找不到在FirstName上检索属性的方法。

我相信有一种方法可以读取属性数据。。。至少ASP.NET能够读取验证并显示指定的属性,而不以属性(property:(为目标。

您找错地方了:当使用"braceles";在C#中的record语法中,放置在成员上的属性实际上是参数属性

你可以从[Display] String FirstName中获得DisplayAttribute,如下所示:

ParameterInfo[] ctorParams = typeof(TestRecord)
.GetConstructors()
.Single()
.GetParameters();

DisplayAttribute firstNameDisplayAttrib = ctorParams
.Single( p => p.Name == "FirstName" )
.GetCustomAttributes()
.OfType<DisplayAttribute>()
.Single();

最新更新