110,534
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace PropertyTest
{
class A
{
public string p1 { get; set; }
}
class B
{
public List<A> p2 { get; set; }
}
class Program
{
static void Main(string[] args)
{
B b = new B();
A a = new A();
a.p1 = "test";
b.p2.Add(a);
getproperty(b);
}
static void getproperty<T>(T t)
{
Type type = t.GetType();
foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
object value = info.GetValue(t, null);
if (info.PropertyType.IsClass && info.PropertyType.ToString() != "System.String")
{
if (info.PropertyType.IsGenericType)
{
//这时候这个T就已经实例成 类B 导致 强制转换失败 求教一下 该怎么处理
foreach (T te in (List<T>)value)
{
getproperty(te);
}
}
}
else
{
Console.WriteLine("{0}={1}", info.Name, value.ToString());
}
}
}
}
}
static void Main(string[] args)
{
B b = new B(){p2=new List<A>()};
A a = new A();
a.p1 = "test";
b.p2.Add(a);
getproperty(b);
}
static void getproperty<T>(T t)
{
Type type = t.GetType();
foreach (PropertyInfo info in type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
object value = info.GetValue(t, null);
if (info.PropertyType.IsClass && info.PropertyType.ToString() != "System.String")
{
if (info.PropertyType.IsGenericType)
{
//这时候这个T就已经实例成 类B 导致 强制转换失败 求教一下 该怎么处理
foreach (var te in (List<A>)value)
{
getproperty(te);
}
}
}
else
{
Console.WriteLine("{0}={1}", info.Name, value.ToString());
}
}
}