//我有这个班级
public class SCHOOL
{
public int ID { get; set; }
public string Name { get; set; }
public string Country{ get; set; }
public decimal Total{ get; set; }
}
//和另一个类型不同的类
public class CLASS_2
{
public string Student { get; set; }
public DateTime Graduate { get; set; }
}
//我可以添加不同类型的第3类和第4类
//我用我的数据填充列表
static void Main()
{
List < SCHOOL> FirstClass = new List < SCHOOL>();
FirstClass.Add( new SCHOOL{ID=1,Name="aaa",County="USA",Total=10});
FirstClass.Add( new SCHOOL{ID=1,Name="bbb",County="JAP",Total=7});
FirstClass.Add( new SCHOOL{ID=1,Name="ccc",County="GBR",Total=5});
List < CLASS_2 > SecondClass = new List < CLASS_2 >();
SecondClass.Add( new CLASS_2 {Student =1, Graduate ="2/6/2015"});
SecondClass.Add( new CLASS_2 {Student =1, Graduate ="2/4/2015"});
SecondClass.Add( new CLASS_2 {Student =1, Graduate ="2/8/2015"});
}
//我想传递第一个List并遍历我的数据
GetmyData ( firstClass);
//并将另一个具有不同类类型的List传递给同一个方法,并循环遍历我的数据
GetmyData ( SenecdClass );
//我想要一个方法来获取列表并循环遍历像数组
这样的数据private void GetmyData <T> ( List<T> newlist )
{
for (int y=0; y < newList.Count; y++)
{
for ( int x=0 ; x < newLsit[y].Colms; x++ )
{
Console.WriteLine ( newList[y][x].value );
}
}
}
答案 0 :(得分:2)
我想说首先你需要使用通用方法:
private void GetMyData(List<T> the List)
{
foreach (T entry in theList)
{
//deal with the entry on the list
}
}
并且为了打印课程的每个属性,我眼中最好的方法是覆盖ToString
但是如果您需要访问每个属性而不仅仅是显示它,则需要反射:
private void GetMyData(List<T> the List)
{
foreach (T entry in theList)
{
foreach (var property in typeof(T).GetProperties())
{
var propertyName = property.Name;
var propertyValue = property.GetValue(entry);
Console.WriteLine("Value of " + propertyName + " is " + propertyValue);
}
}
}
但请记住,并非所有属性都可以阅读。
答案 1 :(得分:0)
static void GetMyData(List theList) {
int count = typeof(T).GetProperties().Count();
for ( int y = 0 ; y < theList.Count ; y++ )
{
for ( int x = 0; x < count; x++ )
{
var propertyName = typeof(T).GetProperties()[x].Name;
var propertyValue = typeof(T).GetProperties()[x].GetValue( theList[y] , null );
var propertyType = typeof(T).GetProperties()[x].PropertyType;
Console.WriteLine(propertyType + " " + propertyName + " " + propertyValue );
}
}
}