2010-11-17 54 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