【问题标题】:Tool to Generate Mock XML With Filled in Values From C# Class使用 C# 类中的填充值生成模拟 XML 的工具
【发布时间】:2017-04-12 20:42:07
【问题描述】:

有时在使用遗留代码时,我需要模拟巨大的对象以通过应用程序...具有类似 200 个属性的对象

有没有一种方法可以从 C# 类生成一个填充了值的模拟 xml 对象,而不是手动构建对象?例如:

public Class Animal
{
    public bool hasWings {get; set;}
    public string name {get; set;}
    public int numberOfFeet {get; set;}
}

会变成:

<Animal>
  <hasWings>true</hasWings>
  <name>string</name>
  <numberOfFeet>0</numberOfFeet>
</Animal>

我不需要实际的真实值...只是占位符

谢谢!

【问题讨论】:

    标签: c# xml testing mocking


    【解决方案1】:

    您可以使用以下方法来完成工作。这将创建一个默认填写值的对象: 更新:添加了处理类类型属性的递归调用

    private static object GetDummyObject(Type type)
    {
        var obj = Activator.CreateInstance(type);
        if (obj != null)
        {
            var properties = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.DeclaredOnly | BindingFlags.Public);
    
            foreach (var property in properties)
            {
                if (property.PropertyType == typeof(String))
                {
                    property.SetValue(obj, property.Name.ToString(), null);
                }
                else if (property.PropertyType.IsArray)
                {
                    property.SetValue(obj, Array.CreateInstance(type.GetElementType(), 0), null);
                }
                else if (property.PropertyType.IsClass)
                {
                    var ob = GetDummyObject(property.PropertyType);
                    property.SetValue(obj, ob, null);
                }
                else
                {
                    var o = GetDefault(property.PropertyType);
                    property.SetValue(obj, o, null);
                }
            }
        }
    
        return obj;
    }
    
    public static object GetDefault(Type type)
    {
        return Activator.CreateInstance(type);
    }
    

    有一些限制。这只会为默认构造函数生成对象,但您始终可以扩展它。

    现在,如果您需要 XML,那么只需序列化从此方法返回的对象。

    【讨论】:

    • 太好了,GetDefault 是什么? VS 抛出它想要一个方法
    • Getmethod 只是 Activator.CreateInstance(property.PropertyType) 的包装。更换线路,你应该很高兴。
    • 很好用...我正在努力扩展您的解决方案,使其递归,以便它可以深入到大型类对象并在那里设置值...如果有一个子对象,则获得一个空引用异常- 现在上课
    • 我已经更新了处理嵌套类对象的代码。
    • 很好,我已经尝试了上述版本...由于某种原因我无法通过
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    • 2011-03-13
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    相关资源
    最近更新 更多