Reputation: 366
I have base class Animal
, and I created many classes which inherits from it, such as Dog
, Cat
, Monkey
... now I want to implement the feature that based on user input, create the object based on the input so that I can run the override version functions inside them. Something like that:
//Animal.cs
abstract class Animal
{
protected abstract void Func()
}
//Dog(or other animal).cs
class Dog:Animal
{
protected override void Func() {Do something;}
}
//program.cs
public static void main()
{
Animal a = null;
string str = Console.ReadLine();
a = "new str()"; // should have some try-catch module, omit here
}
I have hundreds of animals, so using if
or switch
does not look a good solution; any good methods?
Upvotes: 0
Views: 1006
Reputation: 1614
One way do this would be to use a factory using reflection at runtime. Its not the neatest but will avoid you having to use if statements.
public static class AnimalFactory
{
public static Animal Create(string animalName)
{
var type = Type.GetType(typeof(Animal).Namespace + "." + animalName, throwOnError: false);
if (type == null)
{
throw new InvalidOperationException(animalName.ToString() + " is not a known Animal type");
}
if (!typeof(Animal).IsAssignableFrom(type))
{
throw new InvalidOperationException(type.Name + " does not inherit from Animal");
}
return (Animal)Activator.CreateInstance(type);
}
}
Based upon your namespace it will create an instance of an animal using reflection. You can pass in the animal name from your user input.
Then call it using
var type = AnimalFactory.Create("dog");
Upvotes: 4