Reputation: 634
I would like to associate an object of type AbstractObject
to my current Class.
However, this has to be done in the constructor, since, when I define my Class I don't know which type of object would be associated (only that this is of type AbstractObject
). And I need to construct the associated object in my class (So I can't put an instance as parameter).
So it would be something like:
public abstract class MyClass
{
public MyClass(Type T) where T : AbstractObject
{
(T)Actiocator.CreateInstance(Typeof(T));
//To do
}
}
but this doesn't work. Any idea how to fix this?
Upvotes: 2
Views: 90
Reputation: 1927
Try this:
public abstract class MyClass<T> where T : AbstractObject, new()
{
public MyClass(T type)
{
T instance = new T();
}
}
If you add new()
in the generics constraints, you can call the parameterless constructor of your class.
https://msdn.microsoft.com/en-us/library/bb384067.aspx
Upvotes: -1
Reputation: 9232
Depending on your use case, there are several options.
The simplest way is have the caller construct the object, and pass it in through the constructor:
public MyClass(AbstractObject template)
{
// Do something with template
}
Expanding on the idea above, if you want to have control over the object that the constructor uses, you can provide a static method that creates a Base
object and passes it to the constructor:
private MyClass(AbstractObject template)
{
// Do something with template
}
public MyClass Create<T>() where T : AbstractObject, new()
{
// Create a temporary object just for passing into the private ctor
return new MyClass(new T());
}
I made the constructor private so you can create a new MyClass
object only through the static instance:
MyClass.Create<Concrete>();
Also note I added the new()
constraint, so I can simply write new T
. This is fine if you know that T
is going to a be a derived class of AbstractObject
which is a reference type. If you want to be able to construct MyClass
es from value types such as int
, you can drop the new()
constraint and use reflection.
If you also need to store the object in your class, make the whole class generic:
public class MyClass<T> where T : AbstractObject, new()
{
private T myObject;
public MyClass()
{
this.myObject = new T();
// Do other stuff
}
}
Upvotes: 3
Reputation: 6310
maybe something like this would suit you?
abstract class AbstractObject {}
class Test : AbstractObject
{
public Test()
{
Console.WriteLine("I work");
}
}
class GenTest<T> where T: AbstractObject, new()
{
T obj;
public GenTest()
{
obj = new T();
}
}
public static void Main()
{
var genTestObj = new GenTest<Test>();
}
Upvotes: 0
Reputation: 7352
Create a interface or a abstract class them implement it in the class you want to pass into the current class constructor
public interface ITest
{
// your interface method and properties
}
public class Child : ITest
{
// do your stuff here
}
public abstract class MyClass
{
public MyClass(ITest tes)
{
// do stuff using test
}
}
Upvotes: 0