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

时间:2013-10-22 19:40:00

标签: c# reflection

今天我遇到了以下问题:获取特定属性及其某些属性的值。

假设此代码:

型号:

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上工作。

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

1 个答案:

答案 0 :(得分:3)

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
    }
}