无论如何,我可以将一个元素附加/连接到一个可枚举的 if 条件吗?
Is there anyway i can append /concat an element to an enumerable if condition?
你好,我正在尝试 select 对象中的所有唯一类型 recursively.Is 有什么方法我不使用 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();
}
我需要这样的东西:
case 原始类型:yield return type
大小写不是原始类型:Enclosingtype.GetFields().SelectMany(field=>Traverse(field.fieldtype)
当然我也需要它是唯一的,这就是我使用 HashSet 的原因。
看起来你想要这样的东西:
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)));
}
你好,我正在尝试 select 对象中的所有唯一类型 recursively.Is 有什么方法我不使用 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();
}
我需要这样的东西:
case 原始类型:yield return type
大小写不是原始类型:Enclosingtype.GetFields().SelectMany(field=>Traverse(field.fieldtype)
当然我也需要它是唯一的,这就是我使用 HashSet 的原因。
看起来你想要这样的东西:
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)));
}