[英]Is there an easy way of getting all of an objects properties as a string?
I have a class called ReportToDownload that contains several properties. 我有一个名为ReportToDownload的类,其中包含几个属性。 In the Assert part of a test I'm comparing expected and actual lists of ReportToDownload using an equality comparer I have written. 在测试的断言部分中,我正在使用我编写的相等比较器比较ReportToDownload的预期列表和实际列表。 For any items that don't match I was hoping to print out the contents of the expected and actual items as part of the message using: 对于任何不匹配的项目,我希望使用以下方法将预期和实际项目的内容作为消息的一部分打印出来:
actual[i].ToString()
but this just returns the name of the object - ReportToDownload. 但这只是返回对象的名称-ReportToDownload。 Is there any way of easily getting the whole contents of the object as a string? 有什么方法可以轻松地将对象的全部内容作为字符串获取?
Depending on who this is being shown to, a simple "no effort" solution is to use JSON: 根据显示给谁,一个简单的“不费吹灰之力”的解决方案是使用JSON:
Install-Package Newtonsoft.Json
Then... 然后...
JsonConvert.SerializeObject(actual[i])
Rather than using an equality comparison, write a method that compares every individual property using your unit test's framework built-in assertion methods, eg: 而不是使用相等比较,而是使用单元测试的框架内置的断言方法编写一种比较每个单独属性的方法,例如:
public void AssertEquals(ReportToDownload actual, ReportToDownload expected)
{
Assert.That(actual.PropertyA, Is.EqualTo(expected.PropertyA));
Assert.That(actual.PropertyB, Is.EqualTo(expected.PropertyB));
}
The built-in assertion methods will print the expected and actual values appropriately when there is a comparison failure. 当比较失败时,内置的断言方法将适当地打印期望值和实际值。
Most likely, your unit test framework will also allow you to write your own assertions that will print the differences in a custom way, if necessary. 最有可能的是,您的单元测试框架还允许您编写自己的断言,必要时将以自定义方式打印差异。
I don't know how useful this could be, but here's my take: 我不知道这可能有多大用处,但这是我的看法:
public class ClassA
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
public override string ToString()
{
string ret = string.Empty;
foreach (PropertyInfo pi in this.GetType().GetProperties())
{
ret += string.Format("{0}: {1}\r\n", pi.Name, pi.GetValue(this, null).ToString());
}
return ret;
}
}
Used like this: 像这样使用:
ClassA a = new ClassA();
a.Prop1 = "Hello";
a.Prop2 = "World";
var toStringOutput = a.ToString();
You may have to handle more complex property types, but for basic ones, that should work. 您可能必须处理更复杂的属性类型,但对于基本属性类型,它应该起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.