【问题标题】:How to dynamically iterate/detect member types in ValueTuple that has null members? [duplicate]如何动态迭代/检测具有空成员的 ValueTuple 中的成员类型? [复制]
【发布时间】:2018-06-13 17:21:09
【问题描述】:

我正在尝试使用ValueTuple 在泛型方法的参数列表中简洁地输入N 类型列表,然后再迭代该类型列表。

但是,我在迭代类型时遇到了问题,因为最初的 Tuplenull 成员,所以调用 .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&lt;&gt; 类型的类型参数与获取任何其他泛型类型的类型参数完全相同。喜欢Dictionary&lt;TKey, TValue&gt;,标记为重复。
  • 完美,谢谢。我想我是那么专注于使用 Ituple 的索引器,我什至没有考虑过。
  • 不要将其用作欺骗目标,不需要使用反射...

标签: c# reflection tuples c#-7.0 valuetuple


【解决方案1】:

我认为您正在混合数据和元数据。 第一次调用成功,因为 int 是值类型,并且 default(int) 将值分配给 0,所以它可以工作。这不适用于引用类型,因为它们最初被分配给 null。

我相信这里的正确方法是反射 - 并迭代类型的属性,而无需创建实例(因此 new() 限制是多余的)。

public static void IterateTupleMemberTypes<T>() where T : ITuple
{
    var tupleGenericArguments = typeof(T).GetGenericArguments();
    for (var i = 0; i < tupleGenericArguments.Length; ++i)
    {
        Console.WriteLine($"Item{i} Type: {tupleGenericArguments[i].Name}");
    }
}

【讨论】:

  • 必须不同意——如果你坚持使用索引器,反射不会帮助你——即访问数据。您需要使用元数据 - 在这种情况下获取 typeof(T) 的通用参数,我添加了一个代码 sn-p。
  • 糟糕,我已经纠正了,根本没用过ITuple
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 2021-07-21
  • 1970-01-01
相关资源
最近更新 更多