您可以使用反射和数据结构来跟踪每个属性的值(通过等效索引)来实现此操作。
这将自动考虑类中的所有属性,并且您可以通过简单地向ValuesFor
字典添加内容来扩展其他属性类型。
using System;
using System.Collections.Generic;
using System.Reflection;
public class Program
{
private static Dictionary<string, object[]> ValuesFor = new Dictionary<string, object[]>()
{
{ typeof(int).ToString(), new object[] { 0, 1, 2, 3, 4, 5 } },
{ typeof(bool).ToString(), new object[] { true, false } }
};
public static void Main()
{
var properties = typeof(A).GetProperties(BindingFlags.Instance | BindingFlags.Public);
int[] valueIndices = new int[properties.Length];
do
{
createObject(properties, valueIndices);
} while (setNext(properties, valueIndices));
Console.ReadKey();
}
public static bool setNext(PropertyInfo[] properties, int[] valueIndices)
{
for (var i = 0; i < properties.Length; i++)
{
if (valueIndices[i] < ValuesFor[properties[i].PropertyType.ToString()].Length - 1) {
valueIndices[i]++;
for (var j = 0; j < i; j++)
valueIndices[j] = 0;
return true;
}
}
return false;
}
public static void createObject(PropertyInfo[] properties, int[] valueIndices)
{
var a = new A();
for (var i = 0; i < properties.Length; i++)
{
properties[i].SetValue(a, ValuesFor[properties[i].PropertyType.ToString()][valueIndices[i]]);
}
print(a, properties);
}
public static void print(object a, PropertyInfo[] properties)
{
Console.Write("Created : ");
for (var i = 0; i < properties.Length; i++)
Console.Write(properties[i].Name + "=" + properties[i].GetValue(a) + " ");
Console.Write("\n");
}
public class A
{
public int value { get; set; }
public bool foo { get; set; }
public bool bar { get; set; }
public bool boo { get; set; }
}
}
当前,createObject
仅创建对象并调用print
打印对象。相反,您可以将其添加到集合中并使用它运行您的测试(或直接将您的测试放在print
的位置)。
Fiddle - https://dotnetfiddle.net/oeLqc5
代码编辑器 - https://dotnetfiddle.net/oeLqc5