如何递归地查找子属性

本文关键字:查找 属性 递归 何递归 | 更新日期: 2023-09-27 18:19:44

我有一个名为Required() : BaseAttribute的验证属性,我可以使用以下代码跟踪它:(BaseAttribute只实现了IsValid()方法。)

public static String Validate(object Object)
{
    StringBuilder builder = new StringBuilder();
    if (Object != null)
    {
        Type ObjectType = Object.GetType();
        PropertyInfo[] Properties = ObjectType.GetProperties();
        foreach (PropertyInfo Property in Properties)
        {
            object[] Attributes = Property.GetCustomAttributes(typeof(BaseAttribute), true);
            foreach (object Attribute in Attributes)
                builder.AppendLine(((BaseAttribute)Attribute).IsValid(Property, Object));
        }
    }
return builder.ToString();
}

问题是,这是有效的:

class roh {
    [Required()]
    public string dah { get; set; }
}
class main {
    Console.WriteLine(Validate(new roh()));
}

但这不是:

class fus {
    private roh _roh
    public roh Roh {
        get { if (_roh == null)
                  _roh = new roh;
              return _roh; }
        set { _roh = value; }
    }
}
class roh {
    [Required()]
    public string Dah { get; set; }
}
class main {
    Console.WriteLine(Validate(new fus()));
}

如何修改Validate方法,使其无论对象有多深都能递归地找到自定义属性?

如何递归地查找子属性

您可以使用Microsoft企业库。它有一些内置的验证块(在风格上与您在这里使用的类似),我相信它确实支持对象图中的递归对象验证。

您可以引用EntLib验证DLL,并且可以使用内置验证或编写自己的验证。然后,您可以使用一个简单的Validation.Validate(myObject)调用来验证它。

希望这可能会有所帮助:)

您已经说过"递归"这个神奇的词了。对于您访问的每个属性,对其存储的对象调用Validate,瞧。

一个警告是无限递归——如果对象图是一棵树,这将正常工作。如果它更复杂,你需要跟踪你已经访问过的对象。