我有一个非常大的 POCO 对象集合,其中包含几个我需要模拟的子属性......
在使用快速监视时,我看到了我想要的实体......
我正在寻找的是一种扩展方法或一种串起来的方法,这样我就可以去我的单元测试并在那里模拟它......有点:
var myPoco = new Poco {
//here goes whatever i get from my magic method
};
关于如何串接给定对象的所有属性名称和值以便可以分配它的任何内容?
编辑 1:
我正在寻找类似的东西:
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) + "";rn";
}
else
if (i.PropertyType == typeof(Guid))
{
result += "new Guid("" + i.GetValue(obj) + "");rn";
}
else
{
var objAux = i.GetValue(obj);
result += (objAux == null ? "null" : objAux) + ";rn";
}
});
return result.Replace(" = True;", " = true;").Replace(" = False;", " = false;");
}
可以在类上创建一个索引器,该索引器使用反射通过属性名称的字符串值来设置属性。下面是一个示例类:
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);
}
}
}
}
}
然后测试它:
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();
}
}
}
输出:
测试1
测试2
1
阿拉伯数字