如何自动显示类的所有属性及其在字符串中的值?
想象一个具有许多公共属性的类。由于某种原因,不可能将此类重构为更小的子类。
我想添加一个 ToString 覆盖,它返回以下内容:
Property 1: Value of property 1\n Property 2: Value of property 2\n ...
有没有办法做到这一点?
Imagine a class with many public properties. For some reason, it is impossible to refactor this class into smaller subclasses.
I'd like to add a ToString override that returns something along the lines of:
Property 1: Value of property 1\n Property 2: Value of property 2\n ...
Is there a way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为你可以在这里进行一些反思。看一下
Type.GetProperties()
。I think you can use a little reflection here. Take a look at
Type.GetProperties()
.@Oliver 的答案作为扩展方法(我认为很适合)
@Oliver's answer as an extension method (which I think suits it well)
您可以通过反射来做到这一点。
You can do this via reflection.
您可以从 StatePrinter 包 中对状态进行更精细的内省中获取灵感类内省器
You can take inspiration from a more elaborate introspection of state from the StatePrinter package class introspector
如果您有权访问所需类的代码,那么您只需重写
ToString()
方法即可。如果没有,那么您可以使用 Reflections从 Type 对象读取信息:If you have access to the code of the class you need then you can just override
ToString()
method. If not then you can use Reflections to read information from the Type object: