深度查找类实例中的属性类型
我有一个方法可以解析 xml 并从该 xml 创建指定类型的对象。 这一切都是使用泛型完成的,以便为所有类型提供通用方法。
我的问题是我想使用其类型名称(而不是名称)在各个类中搜索属性。 假设属性的类型为“type1”,那么一些类定义声明如下:
class foo1
{
type1 prop1{get;set;}
}
class foo2
{
foo1 prop2{get;set;}
}
class foo3:foo2
{
type2 prop3{get;set;}
}
对于所有上述声明的类,如果我创建对象,那么我想访问该对象的每个实例的 type1
类型属性上面所说的类,即我应该能够从 foo1
、foo2
、foo3type1
的属性值代码>类。随着课程的增加,我真的想要一种通用的方法来做到这一点。
I have a method which parses the xml and creates an object of a specified type from that xml.
This is all done using generics so as to have a common method for all types.
My issue is that I want to search for a property in various classes using its type name (not by the name).
Lets say property has a type "type1" then some of the class definition is declared below:
class foo1
{
type1 prop1{get;set;}
}
class foo2
{
foo1 prop2{get;set;}
}
class foo3:foo2
{
type2 prop3{get;set;}
}
For all the above declared classes, if I create objects then I want to access type1
typed properties for each instance of the above said classes i.e. I should be able to get value of property declared as type1
from objects of foo1
, foo2
, foo3
classes. I really want a generic way to do this as the classes may increase.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是几乎做到这一点的一种方法。缺少的是使用反射,BindingFlags.FlattenHierarchy 不会返回父类的私有方法。将这些类型标记为受保护或公共将解决此问题。 (您还可以手动遍历基类来读取私有成员。)
如果您想在程序集中查找声明给定类型属性的所有类型,您可以编写如下方法:
在执行程序集中查找定义或继承类型
type1
的属性,您可以调用:这会打印出 foo1。如果定义 foo 类的代码修改为 (a) 将
foo1.prop1
设为公共或受保护,以及 (b) 让foo2
继承自foo1
>,然后上面的代码打印:正如预期的那样。
Here is one way to almost do this. What is missing is that using reflection, BindingFlags.FlattenHierarchy does not return private methods of parent classes. Marking these types as protected or public will resolve this. (You could also manually traverse base classes to read private members.)
If you wanted to find all types in an assembly that declare a property of a given type, you could write a method like:
To find classes in the executing assembly that define or inherit a property of type
type1
, you might call:This prints out foo1. If your code defining the foo classes is revised to (a) make
foo1.prop1
public or protected, and (b) makefoo2
inherit fromfoo1
, then the above code prints:as expected.