Answer the question
In order to leave comments, you need to log in
How to bypass the restriction on the absence of parameters in the class constructor of a generic type?
Hello. I am writing a small training raytracer, I want to organize a component-oriented model in it, similar to that used in unity3d. Faced a problem:
There is a class Component . It is simple as an axe:
public class Component
{
private Component(){}
public Component(SceneObject ownerSceneObject)
{
this.ownerSceneObject = ownerSceneObject;
}
public readonly SceneObject ownerSceneObject;
}
public void AddComponent<ComponentType>() where ComponentType:Component, new(SceneObject ownerSceneObject)
{
components.Add(new ComponentType(this));
}
Answer the question
In order to leave comments, you need to log in
I don't like the very idea of such dependence, but I can't understand WHY.
public class Component
{
public Component(SceneObject ownerSceneObject)
{
this.ownerSceneObject = ownerSceneObject;
}
public readonly SceneObject ownerSceneObject;
}
public class SceneObject
{
private List<Component> components;
public void AddComponent<T>() where T : Component
{
var constructor = typeof(T).GetConstructor(new [] { typeof(SceneObject) });
var created = constructor.Invoke(new object[] { this }) as T;
if (created != null)
this.components.Add(created);
}
public SceneObject()
{
this.components = new List<Component>();
}
}
}
You can try that.
public class SceneObject
{
//.....
public void AddComponent<ComponentType>(Func<SceneObject, ComponentType> inst) where ComponentType : Component
{
components.Add(inst(this));
}
public static void Main(string[] args)
{
SceneObject sObj = new SceneObject();
sObj.AddComponent((a) => new Component(a) );
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question