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 に答える