仅当这些属性继承自某个基类时,如何才能在 C# 中递归搜索这些属性?
仅当属性的类型继承自某个基类时,如何递归获取对象的所有属性?
这是我的尝试:
static IEnumerable<PropertyInfo> FindProperties(object objectTree, Type targetType)
{
if (objectTree.GetType().IsAssignableFrom(targetType))
{
var properties = objectTree.GetType().GetProperties();
foreach (var property in properties)
{
yield return property;
}
foreach (var property in FindProperties(properties, targetType))
{
yield return property;
}
}
}
所以我可以调用,
var allPropertiesOfPageTypes = FindProperties(someClass, typeof(Page));
但是,返回的属性数量始终为零。我做错了什么?
编辑:
我不确定这是否重要,但子类是通用类:
public abstract class MasterPage<T> : BasePage<T> where T : MasterPage<T>
继承:
public abstract class BasePage<T> : Page where T : BasePage<T>
从 Master/BasePage 继承的东西似乎为 IsAssignableFrom
返回 false?
How can I recursively get all the properties of an object only if the type of the property inherits from some base class?
This was my attempt:
static IEnumerable<PropertyInfo> FindProperties(object objectTree, Type targetType)
{
if (objectTree.GetType().IsAssignableFrom(targetType))
{
var properties = objectTree.GetType().GetProperties();
foreach (var property in properties)
{
yield return property;
}
foreach (var property in FindProperties(properties, targetType))
{
yield return property;
}
}
}
So I could call,
var allPropertiesOfPageTypes = FindProperties(someClass, typeof(Page));
However, the number of properties returned is always zero. What am I doing wrong?
Edit:
I'm not sure if this matters but the subclasses are generic classes:
public abstract class MasterPage<T> : BasePage<T> where T : MasterPage<T>
That inherits:
public abstract class BasePage<T> : Page where T : BasePage<T>
Things that inherit from Master/BasePage seem to be returning false for IsAssignableFrom
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
仅当您具有正确的类型并且需要实例而不是属性本身时才需要递归:
You need to only recurse when you have the right type, and you need an instance, not the property itself:
为了验证一个对象是否继承自另一个类,您必须执行与您正在执行的操作相反的操作:
这与以下方式类似:
In order to verify if an object inherits from another class you have to do the opposite of what you are doing:
this works in a similar way to:
也许这可以工作?
Maybe this could work?