[英]How to stringfy a POCO object
I have a really large collection of POCO objects with several sub-properties that i need to mock... 我有很多需要模拟的子属性的POCO对象的集合很大...
While using quick-watch, i see the entity as i wanted it to be... 使用快速观看时,我看到的实体就像我想要的那样。
What i'm looking for is sort of a extension method or a way to stringfy it so i can go to my unit test and mock it there... sort of: 我正在寻找的是某种扩展方法或一种stringfy的方式,这样我就可以进行单元测试并在那里进行模拟...
var myPoco = new Poco {
//here goes whatever i get from my magic method
};
any on how to stringfy all the properties names and values of a given object so that it can be assignable? 关于如何对给定对象的所有属性名称和值进行字符串化以使其可分配的任何方法?
EDIT 1: 编辑1:
I'm looking for something like: 我正在寻找类似的东西:
public static string StringFy(this object obj, string prefix)
{
string result = "";
obj.GetType().GetProperties().ToList().ForEach(i =>
{
result += prefix + "." + i.Name + " = ";
if (i.PropertyType == typeof(string))
{
result += "\"" + i.GetValue(obj) + "\";\r\n";
}
else
if (i.PropertyType == typeof(Guid))
{
result += "new Guid(\"" + i.GetValue(obj) + "\");\r\n";
}
else
{
var objAux = i.GetValue(obj);
result += (objAux == null ? "null" : objAux) + ";\r\n";
}
});
return result.Replace(" = True;", " = true;").Replace(" = False;", " = false;");
}
You could create an indexer on your class that uses reflection to set properties via string value of the property name. 您可以在类上创建一个索引器,该索引器使用反射通过属性名称的字符串值设置属性。 Here is a sample class:
这是一个示例类:
using System.Reflection;
namespace ReflectionAndIndexers
{
class ReflectionIndexer
{
public string StrProp1 { get; set; }
public string StrProp2 { get; set; }
public int IntProp1 { get; set; }
public int IntProp2 { get; set; }
public object this[string s]
{
set
{
PropertyInfo prop = this.GetType().GetProperty(s, BindingFlags.Public | BindingFlags.Instance);
if(prop != null && prop.CanWrite)
{
prop.SetValue(this, value, null);
}
}
}
}
}
and then test it: 然后对其进行测试:
using System;
namespace ReflectionAndIndexers
{
class Program
{
static void Main(string[] args)
{
var ri = new ReflectionIndexer();
ri["StrProp1"] = "test1";
ri["StrProp2"] = "test2";
ri["IntProp1"] = 1;
ri["IntProp2"] = 2;
Console.WriteLine(ri.StrProp1);
Console.WriteLine(ri.StrProp2);
Console.WriteLine(ri.IntProp1);
Console.WriteLine(ri.IntProp2);
Console.ReadLine();
}
}
}
Output: 输出:
test1
测试1
test2
测试2
1
1个
2
2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.