这使用反射完成了技巧(只需更改 Console.WriteLine 以转到您的文件):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class Program
{
public static void Main()
{
ListOfVariablesToSave myListOfVariablesToSave = new ListOfVariablesToSave();
foreach (PropertyInfo pi in myListOfVariablesToSave
.GetType()
.GetProperties( BindingFlags.Public |
BindingFlags.Instance |
BindingFlags.DeclaredOnly )
// Only get the properties of type List<int>
// Actual PropertyType looks like:
// System.Collections.Generic.List`1[System.Int32]
.Where(p => p.PropertyType.ToString().Contains("List") &&
p.PropertyType.ToString().Contains("System.Int32"))
)
{
Console.WriteLine(pi.Name);
(pi.GetValue(myListOfVariablesToSave) as List<int>).ForEach(i => Console.WriteLine(i));
}
}
}
public class ListOfVariablesToSave : List<List<int>>
{
public List<int> controlDB { get; set; }
public List<int> interacDB { get; set; }
// Added this property to show that it doesn't get used in the above foreach
public int Test {get; set;}
public ListOfVariablesToSave()
{
controlDB = new List<int> { 1, 2, 3 };
interacDB = new List<int> { 21, 22, 23 };
Add(controlDB);
Add(interacDB);
}
}
结果:
controlDB
1
2
3
interacDB
21
22
23
在此处查看工作示例... https://dotnetfiddle.net/4yyc8Q
更新
使用 Matt Burland 的类结构不那么麻烦(同样,只需替换 Console.WriteLine 即可转到您的文件)
using System;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
ListOfVariablesToSave myListOfVariablesToSave = new ListOfVariablesToSave();
myListOfVariablesToSave.ForEach(m => {
Console.WriteLine(m.Name);
m.ForEach(m1 => Console.WriteLine(m1));
});
}
}
public class ListOfVariablesToSave : List<ListOfThings<int>>
{
public ListOfThings<int> controlDB { get; set; }
public ListOfThings<int> interacDB { get; set; }
public ListOfVariablesToSave()
{
controlDB = new ListOfThings<int>() { 1, 2, 3 };
controlDB.Name = "controlDB";
interacDB = new ListOfThings<int>() { 21, 22, 23 };
interacDB.Name = "interacDB";
Add(controlDB);
Add(interacDB);
}
}
public class ListOfThings<T> : List<T>
{
public string Name { get; set; }
public ListOfThings() : base() { }
}
结果:
controlDB
1
2
3
interacDB
21
22
23
在此处查看工作示例... https://dotnetfiddle.net/CKsIFo