您好我试图以递归方式选择对象内的所有唯一类型。有什么方法我不使用new Type[]{ }
内容或三元运算符?
class Con
{
public int a;
}
class Right
{
public Con x;
public int a;
public double b;
}
public static HashSet<Type> TypeHash = new HashSet<Type>();
public static IEnumerable<Type> Traverse(Type enclosingType)
{
return (enclosingType.IsPrimitive)
? new Type[] { TypeHash.Add(enclosingType) ? enclosingType : null }
: enclosingType.GetFields().AsEnumerable()
.SelectMany(fieldinfo => Traverse(fieldinfo.FieldType)
.Concat(new Type[] { (TypeHash.Add(fieldinfo.FieldType)) ? fieldinfo.FieldType : null }));
}
static void Main(string[] args)
{
Con myconnect = new Con { a = 5 };
var c = Traverse(new Right { a = 2, b = 3 }.GetType()).Where(x=>x!=null).ToList();
}
我需要类似的东西:
案例原始类型:yield return type
case not primitive type:Enclosingtype.GetFields().SelectMany(field=>Traverse(field.fieldtype)
当然我需要它也是独一无二的,这就是我使用HashSet的原因。
答案 0 :(得分:2)
看起来你想要这样的东西:
public static IEnumerable<Type> Traverse(Type enclosingType)
{
if (enclosingType.IsPrimitive) // string is not a primitive... think about this condition again
{
yield return enclosingType;
}
else
{
foreach (var type in enclosingType.GetFields().SelectMany(f => Traverse(f.FieldType)))
{
yield return type;
}
}
}
用法:
static void Main(string[] args)
{
var result = new HashSet<Type>(Traverse(typeof(Right)));
}