我想拥有一个具有原始类型的对象的所有属性,如果该对象与另一个类有关系,我想拥有另一个类的原始属性
问题是如果实体A有实体B而B有A,我该怎么办
在简单的情况下,通过使用反射我可以得到第一级的原始属性,但是,我不能进入实体B并再次获得A的原始属性,将创建一个循环,你提供什么?
public class A
{
public string Name{get;set;}
public B B{get;set;}
}
public class B
{
public string Category{get;set;}
public A A{get;set;}
}
Run Code Online (Sandbox Code Playgroud)
您可以跟踪访问类型以避免递归:
public class A
{
public string Name { get; set; }
public B B { get; set; }
}
public class B
{
public string Category { get; set; }
public A A { get; set; }
}
class Program
{
static void Main()
{
var result = Visit(typeof(A));
foreach (var item in result)
{
Console.WriteLine(item.Name);
}
}
public static IEnumerable<PropertyInfo> Visit(Type t)
{
var visitedTypes = new HashSet<Type>();
var result = new List<PropertyInfo>();
InternalVisit(t, visitedTypes, result);
return result;
}
private void InternalVisit(Type t, HashSet<Type> visitedTypes, IList<PropertyInfo> result)
{
if (visitedTypes.Contains(t))
{
return;
}
if (!IsPrimitive(t))
{
visitedTypes.Add(t);
foreach (var property in t.GetProperties())
{
if (IsPrimitive(property.PropertyType))
{
result.Add(property);
}
InternalVisit(property.PropertyType, visitedTypes, result);
}
}
}
private static bool IsPrimitive(Type t)
{
// TODO: put any type here that you consider as primitive as I didn't
// quite understand what your definition of primitive type is
return new[] {
typeof(string),
typeof(char),
typeof(byte),
typeof(sbyte),
typeof(ushort),
typeof(short),
typeof(uint),
typeof(int),
typeof(ulong),
typeof(long),
typeof(float),
typeof(double),
typeof(decimal),
typeof(DateTime),
}.Contains(t);
}
}
Run Code Online (Sandbox Code Playgroud)