Reputation: 119
So, here's the deal. I have an interface called IBehavior. Each one of my Entity's has a variable: private IBehavior _behavior
. Each Entity also has a variable: public string Behavior
. Upon loading my entitys the string is filled from an xml file. Subsequently a function called init()
is called on all entitys. This method takes the string and uses this line of code to call the desired constructor: Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(null);
.
Unfortunately, the Invoke() method returns something of type Object, and the _behavior variable wont accept this without a cast. I have tried this approach:
_behavior = (IBehavior)Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(null);
.
All this did was tell me that my _bahavior
variable was null and therefore this could not happen. I'm probably using GetConstructor()
incorrectly. Can someone please point me in the right direction?
Init Function:
public void Init()
{
if (Behavior == "null" || Behavior == "none")
{
_behavior = null;
return;
}
_behavior = (IBehavior) Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(new object(), null);
}
Upvotes: 1
Views: 196
Reputation: 16878
To create type from its name use:
_behavior = (IBehavior)Activator.CreateInstance(Type.GetType(Behavior));
The other problem with your code is that you are calling constructor on new object()
because you use MethodBase.Invoke(Object, Object[])
method:
.GetConstructor(Type.EmptyTypes).Invoke(new object(), null)
and by specifying only array of object, you use ConstructorInfo.Invoke(Object[])
method:
_behavior = (IBehavior)Type.GetType(Behavior)
.GetConstructor(Type.EmptyTypes)
.Invoke(new object[] { });
Note: If you receive ArgumentNullException
from Activator.CreateInstance
, remember that type must be specified with namespace (if defined in the same assembly), like:
Activator.CreateInstance(Type.GetType("ConsoleApplication.SomeClass"))
Upvotes: 3