gpt4 book ai didi

c# - 检测对象是否为 ValueTuple

转载 作者:可可西里 更新时间:2023-11-01 08:59:04 25 4
gpt4 key购买 nike

我有一个用例,我需要检查某个值是否为 C# 7 ValueTuple,如果是,则循环遍历每个项目。我尝试检查 obj is ValueTupleobj is (object, object) 但它们都返回 false。我发现我可以使用 obj.GetType().Name 并检查它是否以 "ValueTuple" 开头,但这对我来说似乎很蹩脚。欢迎任何替代方案。

我也有获取每个项目的问题。我尝试使用此处找到的解决方案获取 Item1:How do I check if a property exists on a dynamic anonymous type in 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
}
}

最佳答案

结构在 C# 中不继承,所以 ValueTuple<T1> , ValueTuple<T1,T2> , ValueTuple<T1,T2,T3>等等是不继承自 ValueTuple 的不同类型作为他们的基地。因此,obj is ValueTuple检查失败。

如果您正在寻找 ValueTuple使用任意类型参数,您可以检查类是否为 ValueTuple<,...,>如下:

private static readonly Set<Type> ValTupleTypes = new HashSet<Type>(
new Type[] { typeof(ValueTuple<>), typeof(ValueTuple<,>),
typeof(ValueTuple<,,>), typeof(ValueTuple<,,,>),
typeof(ValueTuple<,,,,>), typeof(ValueTuple<,,,,,>),
typeof(ValueTuple<,,,,,,>), typeof(ValueTuple<,,,,,,,>)
}
);
static bool IsValueTuple2(object obj) {
var type = obj.GetType();
return type.IsGenericType
&& ValTupleTypes.Contains(type.GetGenericTypeDefinition());
}

要根据类型获取子项,您可以使用不是特别快的方法,但应该可以解决问题:

static readonly IDictionary<Type,Func<object,object[]>> GetItems = new Dictionary<Type,Func<object,object[]>> {
[typeof(ValueTuple<>)] = o => new object[] {((dynamic)o).Item1}
, [typeof(ValueTuple<,>)] = o => new object[] {((dynamic)o).Item1, ((dynamic)o).Item2}
, [typeof(ValueTuple<,,>)] = o => new object[] {((dynamic)o).Item1, ((dynamic)o).Item2, ((dynamic)o).Item3}
, ...
};

这会让你这样做:

object[] items = null;
var type = obj.GetType();
if (type.IsGeneric && GetItems.TryGetValue(type.GetGenericTypeDefinition(), out var itemGetter)) {
items = itemGetter(obj);
}

关于c# - 检测对象是否为 ValueTuple,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46707556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com