在 C# 中获取属性示例的属性

本文关键字:属性 获取 | 更新日期: 2023-09-27 18:36:24

>今天我面临以下问题:获取特定属性及其某些属性的值。

假设以下代码:

型:

public class ExampleModel : SBase
{
    [MaxLength(128)]
    public string ... { get; set; }
    [ForeignKey(typeof(Foo))] // Here I wanna get the "typeof(Foo)" which I believe it is the value of the attr
    public int LocalBarId { get; set; }
    [ForeignKey(typeof(Bar))]
    public int LocalFooId { get; set; }
    [ManyToOne("...")]
    public ... { get; set; }
}

然后在另一个类中,我想获取所有"ForeignKey"属性及其值,以及更多它们各自的属性,但是我不知道在实践中如何做到这一点。(最后,将所有这些信息放入任何数组中会很好。

我最近在写一篇反思。这样做的理念是只获得特定属性。下面是一段代码:

foreach (var property in this.allProperties)
{
    var propertyItself = element.GetType().GetProperty(property.Name);
    if (propertyItself.PropertyType != typeof(Int32))
    { continue; }
    if (propertyItself.ToString().Contains("Global") && (int)propertyItself.GetValue(element, null) == 0)
    { // doSomething; }
    else if (propertyItself.ToString().Contains("Local") && (int)propertyItself.GetValue(element, null) == 0)
    { // doSomething; }
}

所以基本上我只对获取 int 类型的属性感兴趣,如果该属性是我所期望的,那么我会在 em 上工作。

好吧,我希望通过这次对话,任何人或某人可以帮助我,或者,只给出一个关于如何做到这一点的基本想法。提前感谢!:)

在 C# 中获取属性示例的属性

var properties = typeof(ExampleModel).GetProperties();
foreach (var property in properties)
{
    foreach (ForeignKeyAttribute foreignKey in
                       property.GetCustomAttributes(typeof(ForeignKeyAttribute)))
    {
        // you now have property's properties and foreignKey's properties
    }
}