从记录中获取属性
我正在寻找一种方法来获取记录构造函数“字段”上定义的属性。
// 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:
)。
I'm looking for a way to get the attribute defined on a record constructor "field".
// 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 );
I'm able to get the attribute on LastName
targeting the property (using property:
).
But I'm not able to find a way to retrieve the attribute on FirstName
.
I'm sure there is a way to read the attribute data... at least ASP.NET is able to read validation and display attributes specified without targeting the property (property:
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

您找错了地方:在 C# 中使用“无括号”
record
语法时,放置在成员上的属性实际上是参数属性。您可以从
[Display] String FirstName
获取DisplayAttribute
,如下所示:You're looking in the wrong place: when using the "braceless"
record
syntax in C#, attributes placed on members are actually parameter attributes.You can get the
DisplayAttribute
from[Display] String FirstName
like so: