打印不同类的所有属性? [英] Print all properties of different classes ?

查看:60
本文介绍了打印不同类的所有属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个名为Person的基本抽象类,我还有一些继承了这个类的其他calsses,我创建了一个Person列表:

Hi,

I have base abstract class named Person, and I have some other calsses that inherited this class, I create a list of Person :

List<person> baseP = new List<person>();
baseP[0].Add(new Worker("Yaakov",43));
baseP[1].Add(new Manager("David",54,"Intel"));
baseP[2].Add(new Teacher("Ella",33,"A"));





现在我想要打印此列表和工人类型的所有属性,每个属性都有其他额外属性...



扫描此列表和打印的最佳方法是什么所有属性???



谢谢



now I want to print this list and all properties of the workers types, each one of them has other additional propertis...

what is the best way to scan this list and print all properties ???

Thanks

推荐答案

您可以使用反射来调查属性。例如,您可以使用 GetProperties 列出类型的属性[ ^ ]方法。



很少有可能有趣的文章:

- .NET中的反思 [ ^ ]

- C#:使用反射和自定义属性来映射对象属性 [ ^ ]

- 在C#中循环使用对象的属性 [ ^ ]
You can use reflection to investigate the properties. For example you can list the properties of a type using GetProperties[^] method.

Few articles that might be interesting:
- Reflection in .NET[^]
- C#: Using Reflection and Custom Attributes to Map Object Properties[^]
- Looping through Object's properties in C#[^]


这很简单。



请参阅:

https://msdn.microsoft.com/en-us/library/58918ffs。 aspx [ ^ ](从类中获取 System.Type 对象),

然后: https://msdn.microsoft.com/en-us/library/kyaxdd3x%28v=vs.110%29.aspx [ ^ ]。



-SA
This is easy.

Please see:
https://msdn.microsoft.com/en-us/library/58918ffs.aspx[^] (to get System.Type object from a class),
and then: https://msdn.microsoft.com/en-us/library/kyaxdd3x%28v=vs.110%29.aspx[^].

—SA


我不会沿着反射道路走下去。它很慢,而且很难看。特别是因为事先知道了所有对象类型。



在基类中实现抽象方法并在继承的类中覆盖它以显示显示值,或者更好,在所有继承的类中使用ToString()覆盖。这两个选项使您可以完全控制要为每个继承类型显示的信息。



接下来,只需遍历列表并调用ToString()或您自己的方法在每个对象上显示必要的信息。
I wouldn't go down the reflection road. It's slow, and it's ugly. Especially since you know all your object types beforehand.

Implement an abstract method in your base class and override it in your inherited classes to show the display value, or better yet, use ToString() overrides in all inherited classes. Both options give you full control over the information you want to display for each inherited type.

Next, just loop through the list and call ToString() or your own method on every object to display the necessary information.


这篇关于打印不同类的所有属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆