1

当我弄清楚如何在 C# 中为 ASP.NET 项目创建子类时,我感觉很聪明,然后我发现了一个问题——我不知道如何根据 SQL 查询的结果创建正确子类的对象.

假设您有一个名为 Animal 的类和两个名为 Zebra 和 Elephant 的子类。你明白吗?

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

所以,原则上,Animal 类应该有一个静态方法:

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

class Zebra : Animal{
 //some code here
}

这是可能的还是我只是简单地理解了子类的想法是错误的。很明显,我不是 OO 专家。

在此先感谢,杰克

4

3 回答 3

5

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

于 2010-11-17T19:48:02.187 回答
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");
    }
}
于 2010-11-17T20:49:31.877 回答
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());
}
于 2010-11-17T19:54:29.223 回答