C# 如何确定元组类型?

C# 如何确定元组类型?,c#,.net,tuples,C#,.net,Tuples,显然,ITuple是内部的,禁用了诸如typeof(ITuple)之类的解决方案。IsAssignableFrom(type)。或者,确定Tuple到Tuple的最有效方法是什么?最好使用不进行类型名称比较的解决方案。尝试以下方法: public static bool IsTupleType(Type type, bool checkBaseTypes = false) { if (type == null) throw new ArgumentNullExceptio

显然,
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;
}
publicstaticboolistupletype(类型类型,boolcheckbasetypes=false)
{
if(type==null)
抛出新ArgumentNullException(nameof(type));
if(type==typeof(元组))
返回true;
while(type!=null)
{
if(type.IsGenericType)
{
var genType=type.GetGenericTypeDefinition();
if(genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组)
||genType==typeof(元组))
返回true;
}
如果(!checkBaseTypes)
打破
type=type.BaseType;
}
返回false;
}

我知道OP不喜欢比较类型名,但作为参考,我提供了一个简短的解决方案,用于确定类型是否为值元组:

var x = (1, 2, 3);

var xType = x.GetType();   
var tType = typeof(ValueTuple);   

var isTuple = xType.FullName.StartsWith(tType.FullName)

您可以添加
xType.Assembly==tType.Assembly
以确定。

您所说的“确定”是什么意思?你有一些对象的例子以及你想从中学习什么吗?虽然你不能直接使用
typeof(ITuple)
,但你仍然可以使用
Type.GetType(“System.ITuple,mscorlib”)
来获得它。@JonathonReinhart我相信他问的是,“我有一个目标。我不确定它是否是一个元组,也不知道使用了多少类型参数,或者它们是什么,即使它是一个元组。我怎么查?“@vcsjones-不涉及元组对象,只为从
Tuple
Tuple
@toplel32的任何元组类型键入对象。不,如果将来的.NET版本更改,依赖某些内部功能可能会破坏程序。这似乎是唯一可靠的解决方案。请其次,我希望使此方法更可靠。您可能希望重命名为
IsTypeOfTuple
,因为
IsTuple
建议处理实例。请注意
Tuple
是静态的。我知道,但它毕竟是Tuple。您可以像IsTypeOfTuple(typeof(Tuple))一样调用它