gpt4 book ai didi

.net - 反射,从好友类获取DataAnnotation属性

转载 作者:行者123 更新时间:2023-12-04 20:00:58 28 4
gpt4 key购买 nike

我需要检查属性是否在其伙伴类中定义了特定属性:

[MetadataType(typeof(Metadata))]
public sealed partial class Address
{
private sealed class Metadata
{
[Required]
public string Address1 { get; set; }

[Required]
public string Zip { get; set; }
}
}

如何检查定义了哪些属性 Required属性?

谢谢你。

最佳答案

可以通过探索嵌套类型来完成:

public IEnumerable<PropertyInfo> GetRequiredProperties()
{
var nestedTypes = typeof(Address).GetNestedTypes(BindingFlags.NonPublic);

var nestedType = nestedTypes.First(); // It can be done for all types

var requiredProperties =
nestedType.GetProperties()
.Where(property =>
property.IsDefined(typeof(RequiredAttribute), false));

return requiredProperties;
}

用法示例:
[Test]
public void Example()
{
var requiredProperties = GetRequiredProperties();
var propertiesNames = requiredProperties.Select(property => property.Name);

Assert.That(propertiesNames, Is.EquivalentTo(new[] { "Address1", "Zip" }));
}

关于.net - 反射,从好友类获取DataAnnotation属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2611272/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com