如何递归查找子属性属性

时间:2012-01-09 07:38:52

标签: c# attributes

我有一个名为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方法,以便无论对象有多深,它都可以递归方式找到自定义属性?

2 个答案:

答案 0 :(得分:2)

您可以使用Microsoft Enterprise Library。它有一些构建在验证块中(类似于你在这里使用的样式)并且支持在对象图中对递归对象进行验证。我相信。

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

希望这可能有所帮助:)

答案 1 :(得分:1)

你已经说过了神奇的词 - 递归。对于您访问的每个属性,请在它存储的对象上调用Validate,然后瞧。

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

相关问题