使用反射动态重写 ToString()
我通常重写 ToString() 方法来输出属性名称和与其关联的值。我有点厌倦了手工编写这些内容,所以我正在寻找一个动态的解决方案。
主要:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
TestingClass:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
sb.Append(this.GetType().GetProperty(property.Name).Name);
sb.Append(System.Environment.NewLine);
}
}
return sb.ToString();
}
}
当前输出:
Prop1: System.String Prop1
Prop2: System.String Prop2
所需输出:
Prop1: blah1
Prop2: blah2
我愿意接受其他解决方案,它不必使用反射,它只需产生所需的输出。
I generally override the ToString() method to output the property names and the values associated to them. I got a bit tired of writing these by hand so I'm looking for a dynamic solution.
Main:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
TestingClass:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
sb.Append(this.GetType().GetProperty(property.Name).Name);
sb.Append(System.Environment.NewLine);
}
}
return sb.ToString();
}
}
This currently outputs:
Prop1: System.String Prop1
Prop2: System.String Prop2
Desired Output:
Prop1: blah1
Prop2: blah2
I'm open for other solutions, it doesn't have to use reflection, it just has to produce the desired output.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
这对我有用:
要使其在任何地方都可用,您可以创建一个扩展。
不可能重写扩展中的方法,但它仍然可以简化您的生活。
然后,您可以对每个对象调用
ToStringExtension()
。缺点是,它不能完美地处理列表等,例如:
This works for me:
To make it available everywhere you can create an Extension.
It's not possible to override methods in an Extension, but still it should simplify your life.
You can then call
ToStringExtension()
on every object.Downside is, it doesn't work perfectly for lists etc., example:
这是一个扩展,它将报告标准类型,例如 string、int 和 Datetime,但也会报告字符串列表(如下所示在
AccessPoints
中,上面的答案无法处理)。请注意,输出是对齐的,例如:下面是扩展,它接受任何类型,只要它是一个类。然后它反映公共和私有属性,如果它们不为空,则报告它们。
用法
myInstance.ReportAllProperties()
请注意,这是基于我的博客文章 C#: ToString To通过反射报告所有属性,甚至是私有属性,这对正在发生的事情提供了更可靠的解释。
Here is an extension which will report the standard types such as string, int and Datetime but will also report string lists (shown below in
AccessPoints
which the above answer could not handle). Note that the output is aligned such as:Below is the extension which takes in any type as long as its a class. It then reflects off of the public and private properties and if they are not null reports them.
Usage
myInstance.ReportAllProperties()
Note that this is based off my blog article C#: ToString To Report all Properties Even Private Ones Via Reflection which provides a more robust explanation of what is going on.
我会使用 JSON,Serializer 将为您完成所有艰苦的工作:
I would use JSON, Serializer will do all the hard work for you:
这是我发现的,适用于大多数复杂类型(包括列表):
用法:
This is what I found, that works with most compicated-types (including List):
usage:
我自己遇到了这个问题,我正在寻找一个选项来序列化为可读的内容。如果没有只读属性,则 xml 序列化可以给出可读字符串。但是,如果存在只读属性/字段,则不能选择 xml 序列化。
I ran into this myself where I am looking for an option to serialize into something readable. If there are no read only properties xml serialization can give a readable string. However if there are read only properties / fields then xml serialization is not an option.
所以我写了一个扩展方法,调用一个已经解决了所有巫术的库。
“覆盖字符串 ToString()”与(我的)“ToStringDump”....
在展示代码之前,我喜欢扩展方法(本例中为 ToStringDump)的原因..更好的是,我不必猜谜我的 POCO/DTO 对象与 ObjectDump 引用。我相信 POCO 和 DTO 应该“非常非常干净”,甚至在它们自己的程序集中隔离。这样,这些 poco/dto 对象就可以轻松共享。
我的 dotnet core csproj
Nuget 链接:
https://www.nuget.org/packages/ObjectDumper。 NET/
引用:
(来自 https://nugetmusthaves.com/Package/ObjectDumper.NET )
GitHub 链接:
< a href="https://github.com/thomasgalliker/ObjectDumper" rel="nofollow noreferrer">https://github.com/thomasgalliker/ObjectDumper
So I wrote an extension method that calls a library that has already figured out all the voodoo.
"override string ToString()" vs (my) "ToStringDump"....
Before I show the code, the reason I like the extension method (ToStringDump in this case).. better, is that I don't have to riddle my POCO/DTO objects with ObjectDump references. I believe POCOs and DTOs should be "very very clean", and even isolated in their own assembly. This way, these poco/dto objects are easily shared.
My dotnet core csproj
Nuget link:
https://www.nuget.org/packages/ObjectDumper.NET/
Quote:
(from https://nugetmusthaves.com/Package/ObjectDumper.NET )
GitHub link:
https://github.com/thomasgalliker/ObjectDumper