2010-11-17 56 views
1

当我计算出如何在C#中为ASP.NET项目创建子类时,我感觉非常聪明,然后发现了一个问题 - 我不知道如何根据SQL查询的结果创建正确子类的对象。如何根据SQL行中的值创建正确的子类

假设你有一个叫做Animal的类和两个叫Zebra和Elephant的子类。你明白了吗?

我想要做的是执行一个SQL查询,如果返回的行有行[“Type”] =“Zebra”,则加载一个Zebra对象(或者如果它是一个Elephant那么..)。

因此,在原则上,动物类将有一个静态方法:

class Animal{ 
public static Animal Load(DataRow row){ 
    if (row["Type"]=="Zebra"){ 
    return new Zebra(); 
    } 
} 

class Zebra : Animal{ 
//some code here 
} 

这是在所有可能的或有我只是简单的得到了子类的想法是错误的。很明显,我不是面向对象的专家。

由于提前, 杰克

回答

5

可以实现该方法工厂模式。 http://en.wikipedia.org/wiki/Factory_method_pattern

+0

+1:工厂模式可能是最好的解决办法这里没有提前知道代码正在检索哪种类型的动物。 – NotMe 2010-11-17 19:50:57

+0

总是想知道工厂做了什么;-)听起来很有希望。现在关闭。 – 2010-11-17 20:04:39

+0

看起来正是我需要的。谢谢! – 2010-11-17 20:27:09

0

我认为这是罚款:

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()); 
} 
+0

你确定这有效吗?这就是我曾经试过的,并没有它 - 抱怨说不能将动物投给斑马(IRIC) – 2010-11-17 20:04:01

+0

它工作正常。为了简单起见,我将参数行更改为字符串类型。 – 2010-11-17 23:57:59

1

试试这个:

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; } 
} 

而且尝试一下:

class Program 
{ 
    static void Main(string[] args) 
    { 
     IAnimal zebra = Animal.Load("Zebra"); 
     IAnimal elephant = Animal.Load("Elephant"); 
    } 
} 
+0

虽然这不是一个子类,但Zebra不是Animal的子类,它只是实现了接口。虽然我认为这对OP有效,但我不认为它真的回答了这个问题。 – 2010-11-17 20:55:05

+0

谢谢你指出。我误以为斑马和大象类当然应该继承动物。更新了我的答案。 – Jocke 2010-11-17 21:10:45

+0

嗯,我现在很困惑。 – 2010-11-17 22:32:10