コード例 #1
0
        private static object GenerateCollection(Type collectionType, int size, Dictionary <Type, object> createdObjectReferences)
        {
            Type type = collectionType.IsGenericType ?
                        collectionType.GetGenericArguments()[0] :
                        typeof(object);
            object          result             = Activator.CreateInstance(collectionType);
            MethodInfo      addMethod          = collectionType.GetMethod("Add");
            bool            areAllElementsNull = true;
            ObjectGenerator objectGenerator    = new ObjectGenerator();

            for (int i = 0; i < size; i++)
            {
                object element = objectGenerator.GenerateObject(type, createdObjectReferences);
                addMethod.Invoke(result, new object[] { element });
                areAllElementsNull &= element == null;
            }

            if (areAllElementsNull)
            {
                return(null);
            }

            return(result);
        }
コード例 #2
0
        private static object GenerateDictionary(Type dictionaryType, int size, Dictionary <Type, object> createdObjectReferences)
        {
            Type typeK = typeof(object);
            Type typeV = typeof(object);

            if (dictionaryType.IsGenericType)
            {
                Type[] genericArgs = dictionaryType.GetGenericArguments();
                typeK = genericArgs[0];
                typeV = genericArgs[1];
            }

            object          result          = Activator.CreateInstance(dictionaryType);
            MethodInfo      addMethod       = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd");
            MethodInfo      containsMethod  = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey");
            ObjectGenerator objectGenerator = new ObjectGenerator();

            for (int i = 0; i < size; i++)
            {
                object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences);
                if (newKey == null)
                {
                    // Cannot generate a valid key
                    return(null);
                }

                bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey });
                if (!containsKey)
                {
                    object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences);
                    addMethod.Invoke(result, new object[] { newKey, newValue });
                }
            }

            return(result);
        }