显然 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/