【问题标题】:How to stringfy a POCO object如何对 POCO 对象进行字符串化
【发布时间】:2016-06-03 20:09:31
【问题描述】:

我有一个非常大的 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) + "\";\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;");
    }

【问题讨论】:

  • 我以前从来没有真正这样做过,所以我会把它作为评论而不是答案,但我认为你可以在你的类上创建一个索引器,使用反射通过字符串设置属性属性名称的值。使用反射查找以按属性名称设置值,如果您不熟悉我所说的内容,还可以查找索引器。

标签: c# unit-testing mocking poco


【解决方案1】:

您可以在您的类上创建一个索引器,该索引器使用反射通过属性名称的字符串值来设置属性。这是一个示例类:

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

2

【讨论】:

  • 当我可以直接做 ri.StrProp1 = "test1"; 时为什么需要使用反射可能是我在这里遗漏了一些上下文!
  • 我想反过来...给定一个对象,提取一个字符串,让我重新填充它
  • @Leonardo 我猜我很难理解你在问什么。显示一些“假”代码来演示您正在尝试做什么?
  • @Jakotheshadows 请检查编辑 1
  • 在我看来您只是想覆盖 ToString 方法。恐怕您将不得不比您做得更详细。
猜你喜欢
  • 1970-01-01
  • 2016-11-10
  • 2012-07-17
  • 1970-01-01
  • 2015-01-14
  • 1970-01-01
  • 1970-01-01
  • 2019-02-25
相关资源
最近更新 更多