Reputation: 89
i have a class called gameObject and one of it's properties in called component
and is of type object
:
public object component;
and i'm trying to use this object
to act as an object that can hold object of any class you give it. for example
unit c = new unit(...)
gameObject test = new gameObject(...)
test.component = c;
and i want to use the c object through the component object. for example
if(test.component==typeof(unit))
test.component.Draw();//draw is a function of the unit object
is this possible to do? and how do i do it?
Upvotes: 3
Views: 599
Reputation: 5411
As others said - you can cast everything to and from Object
. But you should use some base class of interface to make sure no one will send you Int32
or some other unsuspected type.
But if all supported types have some common method, it's even better to put it in interface. So you can Draw()
anything without casting, not even wondering what it really is.
Variant with empty interface just enforcing proper type:
interface IComponent
{
}
class unit : IComponent
{
//...
}
class enemy : IComponent
{
//...
}
class gameObject
{
IComponent component;//now only objects inheriting IComponent can be assigned here
public void DrawComponent()
{
unit u = component as unit;
if (u != null) {
u.Draw();
}
enemy e = component as enemy;
if (e != null) {
e.DrawIfVisible();
}
}
}
Variant with interface declaring common features:
interface IDrawable
{
void Draw();
}
class unit : IDrawable
{
public void Draw(){;}
//...
}
class enemy : IDrawable
{
public void Draw(){;}
//...
}
class gameObject
{
IDrawable component;
public void DrawComponent()
{
//now you don't need to care what type component really is
//it has to be IDrawable to be assigned to test
//and because it is IDrawable, it has to have Draw() method
if (component != null) {
component.Draw();
}
}
}
Upvotes: 1
Reputation: 24666
To use specific behaviour of an object you have to cast it to its specific type.
Referencig it with an object
variable you can use it only as an object
instance.
Upvotes: 0
Reputation: 726489
typeof(unit)
is an object too, and it is different from component
. You should do component.GetType()
instead:
if(test.component.GetType()==typeof(unit))
This does not check for derived types, but this does:
if(test.component is unit)
Still, this does not let you call Draw
without casting. The easiest way to check and cast at the same time is as follows:
unit u = test.component as unit;
if (u != null) {
u.Draw();
}
Upvotes: 7
Reputation: 5322
Use an interface and make the unit class implement that interface. Define the Draw() method in the interface and declare the component as the type of the interface you defined.
public interface IDrawable
{
void Draw();
}
public IDrawable component;
public class unit : IDrawable
...
Upvotes: 5
Reputation: 8357
Yes, it's called casting. Like this:
if(test.component is unit)
((unit)test.component).Draw();
Upvotes: 5