I was feeling quite clever as I worked out how to create subclasses in C# for an ASP.NET project, then I found a problem - I didn't know how to create an object of the right subclass based on the results of a SQL query.
Say you have a class called Animal and two subclasses called Zebra and Elephant. You get the idea?
What I want to do is perform a SQL query and if the row returned has row["Type"]="Zebra" then load a Zebra object (or if it's an Elephant then..).
So, in principle, the Animal class would have a static method:
class Animal{
public static Animal Load(DataRow row){
if (row["Type"]=="Zebra"){
return new Zebra();
}
}
class Zebra : Animal{
//some code here开发者_运维知识库
}
Is this at all possible or have I just plain got the idea of subclasses wrong. It should be obvious I'm no OO expert.
Thanks in advance, Jake
You can implement the method factory pattern. http://en.wikipedia.org/wiki/Factory_method_pattern
Try this:
public interface IAnimal
{ }
public class Animal : IAnimal
{
public static IAnimal Load(String type)
{
IAnimal animal = null;
switch (type)
{
case "Zebra" :
animal = new Zebra();
break;
case "Elephant" :
animal = new Elephant();
break;
default:
throw new Exception();
}
return animal;
}
}
public class Zebra : Animal
{
public int NrOfStripes { get; set; }
public static Zebra ZebraFactory()
{
return new Zebra();
}
}
public class Elephant : Animal
{
public int LengthOfTrunk { get; set; }
}
And to try it:
class Program
{
static void Main(string[] args)
{
IAnimal zebra = Animal.Load("Zebra");
IAnimal elephant = Animal.Load("Elephant");
}
}
I think it's fine:
public class Animal
{
public static Animal Load(string row)
{
if (row == "Zebra")
{
return new Zebra();
}
else if (row == "Elephant")
{
return new Elephant();
}
return null;
}
}
public class Zebra : Animal
{
public new string ToString()
{
return "Zebra";
}
}
public class Elephant : Animal
{
public new string ToString()
{
return "Elephant";
}
}
static void Main(string[] args)
{
Animal a1 = Animal.Load("Zebra");
System.Console.WriteLine(((Zebra)a1).ToString());
System.Console.WriteLine(((Elephant)a1).ToString()); // Exception
Animal a2 = Animal.Load("Elephant");
System.Console.WriteLine(a2.ToString());
}
精彩评论