注意:我在詢問子類而不是派生類。是類的子類或對象
基本上,我需要做的是檢查一個對象的屬性,並尋找那些具有特定屬性集。
我的問題是,很多特性都是從子類
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;
}
任何想法?
既然是當「小精靈」是一個「中間地球」嗎?我期望「精靈」是「人形」。 – zzzzBov 2013-03-07 23:07:35
@zzzzBov:ItsLateAndHesTired – 2013-03-07 23:33:33
@PieterGeerkens,那麼我希望他打個盹...... ZEN FIRE ZE彈箭! – zzzzBov 2013-03-07 23:50:21