This question already has an answer here:
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.
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.
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()}");
}
}
Usage
public class CustomClass
{
public int ID { get; set; }
}
IterateTupleMemberTypes<(int, string, CustomClass)>();
Aucun commentaire:
Enregistrer un commentaire