c# - 如何确定元组类型?

标签 c# .net tuples

显然 ITuple是内部的,禁用解决方案,例如 typeof(ITuple).IsAssignableFrom(type) .通过替代方法,确定 Tuple<> 的最有效方法是什么?直到 Tuple<,,,,,,,> ?没有类型名称比较的解决方案是更可取的。

最佳答案

试试这个:

public static bool IsTupleType(Type type, bool checkBaseTypes = false)
{
    if (type == null)
        throw new ArgumentNullException(nameof(type));

    if (type == typeof(Tuple))
        return true;

    while (type != null)
    {
        if (type.IsGenericType)
        {
            var genType = type.GetGenericTypeDefinition();
            if (genType == typeof(Tuple<>)
                || genType == typeof(Tuple<,>)
                || genType == typeof(Tuple<,,>)
                || genType == typeof(Tuple<,,,>)
                || genType == typeof(Tuple<,,,,>)
                || genType == typeof(Tuple<,,,,,>)
                || genType == typeof(Tuple<,,,,,,>)
                || genType == typeof(Tuple<,,,,,,,>)
                || genType == typeof(Tuple<,,,,,,,>))
                return true;
        }

        if (!checkBaseTypes)
            break;

        type = type.BaseType;
    }

    return false;
}

关于c# - 如何确定元组类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28772143/

相关文章:

c# - 我如何在 ANTLR 中实现将两个节点合二为一的解析器规则?

c# - 使用 Orleans 的相同 Grain 接口(interface)的多个实现

c# - 我哪里错了?动态创建标签 c#

c# - 将 NetworkStream 复制到 MemoryStream 需要无限 ∞ 天

r - 在一行中为 LHS 分配多个新变量

python - 嵌套循环和元组

c# - Azure Blob 存储下载文件而不是在浏览器中打开

c# - MySQL Linq 使用 .Contains(变量)

c# - 如何确保路径中有尾随目录分隔符?

Python 列表理解、解包和多重操作