tul*_*cra 6 c# ienumerable tuples
如何迭代元组中的项目,当我在编译时不知道元组由哪些类型组成?我只需要一个IEnumerable对象(用于序列化).
private static IEnumerable TupleToEnumerable(object tuple)
{
Type t = tuple.GetType();
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Tuple<,>))
{
var x = tuple as Tuple<object, object>;
yield return x.Item1;
yield return x.Item2;
}
}
Run Code Online (Sandbox Code Playgroud)
在 .NET Core 2.0+ 或 .NET Framework 4.7.1+ 中,有
它来自接口ITuple 接口
var data = (123, "abc", 0.983, DateTime.Now);
ITuple iT = data as ITuple;
for(int i=0; i<iT.Length;i++)
Console.WriteLine(iT[i]);
Run Code Online (Sandbox Code Playgroud)
您可以通过反射来访问属性及其值 Type.GetProperties
var values = tuple.GetType().GetProperties().Select(property => property.GetValue(tuple));
Run Code Online (Sandbox Code Playgroud)
所以你的方法Linq查询会非常简单
private static IEnumerable TupleToEnumerable(object tuple)
{
// You can check if type of tuple is actually Tuple
return tuple.GetType()
.GetProperties()
.Select(property => property.GetValue(tuple));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6462 次 |
| 最近记录: |