I want to create methods which are able to convert lists to tuples (or a struct) by matching types. I would also need to create overloads for several tuple component counts so I could for example call:
var t1 = GetAsTuple<(HealthComponent)>(components);
var t2 = GetAsTuple<(PositionComponent, ModelComponent)>(components);
var t3 = GetAsTuple<(Texture, ModelComponent, PositionComponent)>(components);
Since I have lots of combinations of these I call them component-tuples I want to avoind lots of boilerplate code and want a generic mechanism to fill these tuples.
This is what I tried, obviously it does not compile:
public T GetAsTuple<T>(Component[] components)
where T : ValueTuple<x, y>, new()
where x : Component
where y : Component
{
var t = new T();
t.Item1 = components.OfType<x>().Single();
t.Item2 = components.OfType<y>().Single();
return t;
}
Is it possible what I am trying to do or is there another way to get the desired behavior. I know that I could reach what Iam trying to do with reflection, but this is too slow for the context (game development).
For now I will stick with a reflection based solution.
When I have the time I will implement a T4-template which generates the method overloads for me.