1

注意:我问的是子类,而不是派生类。

基本上,我需要做的是检查对象的属性并查找具有特定属性集的对象。

我遇到的问题是很多属性都来自子类

public class ExampleAttribute : Attribute
{
    public object Whatever { get; set; }
}

public class MiddleEarth
{
    [Example]
    public Type EntityType { get; set; }
}

public class Elf : MiddleEarth
{
    [Example]
    public SubClass ItsLateAndImTired { get; set; }

    public IList<Arg> Args { get; set; }

    //Need to check properties of this object as well
    public class SubClass
    {
        public object SubProperty { get; set; }

        [Example]
        public object SubPropertyWithAttribute { get; set; }
    }

    public class Arg
    {
        [Example]
        public string Something { get; set; }
    }
}

现在,我正在尝试按以下方式进行操作...但由于评论中指出的原因,它不起作用

public List<string> IterateProperties(object _o)
{
    List<string> problems = new List<string>();
    foreach (PropertyInfo info in _o.GetType().GetProperties())
    {
        //All 3 of these will return the exact same thing
        Type thisType = this.GetType();
        Type oType = _o.GetType();
        Type infoType = info.ReflectedType;

        //IsSubClassOf only checks for derived classes, 
        //so it's not the method I'm looking for
        if (info.ReflectedType.IsSubclassOf(this.GetType()))
        {
            object sub = info.GetValue(_o, null);
            if (sub != null)
            {
                problems.AddRange(this.IterateProperties(sub));
            }
        }

        object[] attributes = info.GetCustomAttributes(typeof(ExampleAttribute), true);
        foreach (object o in attributes)
        {
            if (info.GetValue(_o, null) == null)
            {
                problems.Add(String.Format("Attribute {0} in class {1} cannot be null", info.Name, info.ReflectedType.ToString()));
            }
        }
    }

    return problems;
}

有任何想法吗?

4

2 回答 2

1

我相信你正在寻找的是Type.GetNestedTypes()

http://msdn.microsoft.com/en-GB/library/493t6h7t.aspx

于 2013-03-07T23:15:12.847 回答
0

我不确定,但认为 GetProperties 方法有一些可以帮助的标志......

于 2013-03-07T23:08:52.457 回答