我有一个使用案例,需要检查一个值是否是 C# 7 值元组,如果是,则循环遍历每个项目。我尝试了
我还遇到了获取每个项目的问题。我尝试使用此处找到的解决方案获取
更新 - 更多代码
obj is ValueTuple
和 obj is (object, object)
,但这两个都返回 false。我发现我可以使用 obj.GetType().Name
检查它是否以 "ValueTuple"
开头,但这对我来说似乎很糟糕。欢迎任何替代方法。我还遇到了获取每个项目的问题。我尝试使用此处找到的解决方案获取
Item1
:如何在 c# 上检查动态匿名类型上是否存在属性? ,但是 ((dynamic)obj).GetType().GetProperty("Item1")
返回 null。我希望我可以使用 while
来获取每个项目。但是这不起作用。我怎样才能获取每个项目?更新 - 更多代码
if (item is ValueTuple) //this does not work, but I can do a GetType and check the name
{
object tupleValue;
int nth = 1;
while ((tupleValue = ((dynamic)item).GetType().GetProperty($"Item{nth}")) != null && //this does not work
nth <= 8)
{
nth++;
//Do stuff
}
}
((dynamic)item).GetType().GetProperties()
返回一个空数组... :( - James EshItem1
、Item2
等不是属性,而是字段。因此,你需要执行GetType().GetField("Item1")...
。无需进行动态类型转换。 - Evkwhere T : struct
这样的限制将其变成通用的。 - BurnsBA