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

前端之家收集整理的这篇文章主要介绍了c# – 如何确定元组类型?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
显然ITuple是内部的,禁用了诸如typeof(ITuple).IsAssignableFrom(type)之类的解决方案.另外,确定元组的最有效方法是什么?直到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<,>))
                return true;
        }

        if (!checkBaseTypes)
            break;

        type = type.BaseType;
    }

    return false;
}
原文链接:https://www.f2er.com/csharp/92184.html

猜你在找的C#相关文章