gpt4 book ai didi

c# - 如何递归查找子属性属性

转载 作者:行者123 更新时间:2023-11-30 22:32:18 24 4
gpt4 key购买 nike

我有一个名为 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 Enterprise Library .它有一些内置的验证 block (风格与您在这里使用的类似)并且确实支持对象图下的递归对象验证,我相信。

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

希望对您有所帮助:)

关于c# - 如何递归查找子属性属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8785224/

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