CSh*_*ped 0 .net c# system.reflection
我有一堂课,看起来像
public class Employee
{
public string FirstName { get; set; };
public string LastName { get; set; };
public Address Address { get; set; };
}
public class Address
{
public string HouseNo { get; set; };
public string StreetNo { get; set; };
public SomeClass someclass { get; set; };
}
public class SomeClass
{
public string A{ get; set; };
public string B{ get; set; };
}
Run Code Online (Sandbox Code Playgroud)
我想出了一种使用反射来查找类的原始属性的方法,例如字符串,int bool等
但是我还需要找出像ex这样的类中所有复杂类型的列表。带有Class Employee的Address类和Address内的SomeClass类
如果您已经知道如何使用反射,则应该很容易:
private List<Type> alreadyVisitedTypes = new List<Type>(); // to avoid infinite recursion
public static void PrintAllTypes(Type currentType, string prefix)
{
if (alreadyVisitedTypes.Contains(currentType)) return;
alreadyVisitedTypes.Add(currentType);
foreach (PropertyInfo pi in currentType.GetProperties())
{
Console.WriteLine($"{prefix} {pi.PropertyType.Name} {pi.Name}");
if (!pi.PropertyType.IsPrimitive) PrintAllTypes(pi.PropertyType, prefix + " ");
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的电话
PrintAllTypes(typeof(Employee), string.Empty);
Run Code Online (Sandbox Code Playgroud)
会导致:
String FirstName
Char Chars
Int32 Length
String LastName
Address Address
String HouseNo
String StreetNo
SomeClass someclass
String A
String B
Run Code Online (Sandbox Code Playgroud)