问题描述
我正在尝试使用 ValueTuple
在泛型方法的参数列表中简洁地输入 N
类型的列表,然后迭代该类型列表.
I'm trying to make use of ValueTuple
to concisely enter a list of N
types in a generic method's parameter list, and then later iterate that list of types.
但是,我在迭代类型时遇到了问题,因为初始 Tuple
有 null
成员,所以调用 .GetType()
给了我一个 NullReferenceException.
However, I'm running into a problem when iterating the types, because the initial Tuple
has null
members, so calling .GetType()
gives me a NullReferenceException.
我意识到我可以用实际的 Type 对象列表做我需要的事情,但我更喜欢创建元组时允许的非常简洁的语法……当然,因为这样的事情让我很感兴趣:)
I realize I could do what I need with an actual list of Type objects, but I'd prefer the very concise syntax that's allowed when creating tuples... and of course because things like this intrigue me :)
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)>();
推荐答案
我认为您正在混合数据和元数据.第一次调用成功,因为 int 是值类型,并且 default(int) 将该值分配给 0,因此它可以工作.这不适用于引用类型,因为它们最初被分配为 null.
I think you are mixing data and metadata.The first call succeed since int is a value type, and default(int) assigns the value to 0, so it works. This won't do for reference types, since these are assigned initially to null.
我相信这里的正确方法是反射 - 并迭代类型的属性,而无需创建实例(因此 new() 限制是多余的).
I believe the proper approach here is, well, reflection - and iterating over the properties of the type, without the need to create an instance (so the new() restriction is redundant).
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}");
}
}
这篇关于如何在具有空成员的 ValueTuple 中动态迭代/检测成员类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!