【发布时间】:2018-06-13 17:21:09
【问题描述】:
我正在尝试使用ValueTuple 在泛型方法的参数列表中简洁地输入N 类型列表,然后再迭代该类型列表。
但是,我在迭代类型时遇到了问题,因为最初的 Tuple 有 null 成员,所以调用 .GetType() 会给我一个 NullReferenceException。
我意识到我可以使用 Type 对象的实际列表来做我需要的事情,但我更喜欢创建元组时允许的非常简洁的语法......当然因为这样的事情让我很感兴趣 :)
public static void IterateTupleMemberTypes<T>() where T : ITuple, new()
{
var tuple = new T();
for (var i = 0; i < tuple.Length; ++i)
{
//First call to GetType() succeeds, first element is an int.
//Second call to GetType() fails (null ref ex), second element is a string.
Console.WriteLine($"Item{i} Type: {tuple[i].GetType()}");
}
}
用法
public class CustomClass
{
public int ID { get; set; }
}
IterateTupleMemberTypes<(int, string, CustomClass)>();
【问题讨论】:
-
获取
ValueType<>类型的类型参数与获取任何其他泛型类型的类型参数完全相同。喜欢Dictionary<TKey, TValue>,标记为重复。 -
完美,谢谢。我想我是那么专注于使用 Ituple 的索引器,我什至没有考虑过。
-
不要将其用作欺骗目标,不需要使用反射...
标签: c# reflection tuples c#-7.0 valuetuple