c# - 如何检查 ValueTuple 列表是否为 C# 7 中的 List<ValueTuple> 类型

标签 c# types valuetuple

我如何检查 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 对象

所以我尝试了 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)>)));
}

关于c# - 如何检查 ValueTuple 列表是否为 C# 7 中的 List<ValueTuple> 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58519103/

相关文章:

c# - 如何在整个应用程序中添加彩色胶片

c# - Microsoft.WindowsAzure.Storage.Table.TableEntity 未标记为可序列化

c# - ListView 和 Messagebox 奇怪的错误?

python - 比较python中两个动态创建的类类型

c# - 如何动态创建 .NET C# ValueType 元组?

c# - 在 C# 中解构元组的性能损失?

c# - 如果查询标识符之前省略斜杠,为什么带有文件扩展名的请求会返回 404?

haskell - 类型声明 [[Integer] -> Integer]

java - 如何在类定义中的泛型类型中捕获子类型?

c# - C# 7 中 ValueTuple 的 KeyValuePair 命名