首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在C# 7中检查ValueTuple列表是否为List<ValueTuple>类型

如何在C# 7中检查ValueTuple列表是否为List<ValueTuple>类型
EN

Stack Overflow用户
提问于 2019-10-23 16:57:42
回答 1查看 118关注 0票数 1

在不考虑参数类型的情况下,如何检查ValueTuple列表是否为List<ValueTuple>类型?

可能是:

代码语言:javascript
复制
new List<(150, "test")>()
new List<("testy", "test", 148)>()
new List<(true, "blablabla")>()

我尝试过的

代码语言:javascript
复制
 public static bool IsTupleType2(this object tuple)
 {
     return tuple is ITuple;
 }

此扩展方法适用于ValueTuple对象

所以我试着用List<ITuple>,但它不起作用

代码语言:javascript
复制
 public static bool IsTupleType2(this object tuple)
 {
     return tuple is List<ITuple>;
 }

有什么想法吗?

非常感谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-10-23 17:06:56

这是一种相当简单(虽然有点冗长)的方法:

代码语言:javascript
复制
private static readonly Type[] tupleTypes = new[]
{
    typeof(ValueTuple<>), typeof(ValueTuple<,>), typeof(ValueTuple<,,>),
    typeof(ValueTuple<,,,>), typeof(ValueTuple<,,,,>), typeof(ValueTuple<,,,,,>),
    typeof(ValueTuple<,,,,,,>), typeof(ValueTuple<,,,,,,,>)
};

public static bool IsListOfValueTuple(Type type)
{
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))
    {
        var arg = type.GetGenericArguments()[0];
        return arg.IsGenericType && tupleTypes.Contains(arg.GetGenericTypeDefinition());
    }
    return false;
}

public static void Main()
{
    Console.WriteLine(IsListOfValueTuple(typeof(List<(string, int)>)));
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58519103

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档