注意:我问的是子类,而不是派生类。
基本上,我需要做的是检查对象的属性并查找具有特定属性集的属性。
我遇到的问题是很多属性来自子类
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;
}
有什么想法吗?
答案 0 :(得分:1)
我相信你要找的是Type.GetNestedTypes()
答案 1 :(得分:0)
我不确定,但认为GetProperties方法得到了一些可以帮助的标志......