繁体   English   中英

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

[英]How to check if a list of ValueTuple is type of List<ValueTuple> in C# 7

如何检查 ValueTuple 列表是否是List<ValueTuple>类型,而不考虑参数的类型。

它可能是:

new List<(150, "test")>()
new List<("testy", "test", 148)>()
new List<(true, "blablabla")>()

我试过的

 public static bool IsTupleType2(this object tuple)
 {
     return tuple is ITuple;
 }

此扩展方法适用于 ValueTuple object

所以我尝试了List<ITuple>但它不起作用

 public static bool IsTupleType2(this object tuple)
 {
     return tuple is List<ITuple>;
 }

任何想法?

非常感谢。

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

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)>)));
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM