1 回答

TA貢獻1797條經驗 獲得超6個贊
考慮到可能有多個屬性,GetChildTypeOf返回List<Type>對象越好。
private static List<Type> GetChildTypeOf(Type parent)
{
var res = new List<Type>();
var props = parent.GetProperties();
foreach (var prop in props)
{
var propType = prop.PropertyType;
var elementType = propType.GetElementType();
res.Add(elementType);
}
return res;
}
然后你做出你的斷言:
var childType = GetChildTypeOf(typeof(ParentClass));
Assert.True(childType.First() == typeof(ChildClass));
也許如果有一種方法可以返回所有這些元素,并且有一種方法可以通過給定的屬性名稱返回子類型元素,那就更好了。
編輯:以下是查找特定屬性名稱的方式:
private static Type GetSpecificChildTypeOf(Type parent, string propertyName)
{
var propType = typeof(ParentClass).GetProperty(propertyName).PropertyType;
var elementType = propType.GetElementType();
return elementType;
}
并像這樣使用它:
var childType = GetSpecificChildTypeOf(typeof(ParentClass), "Children");
Assert.True(childType == typeof(ChildClass))
編輯:感謝您標記答案!
- 1 回答
- 0 關注
- 135 瀏覽
添加回答
舉報