2010-03-23 26 views
4

只是我学习Generics.When我有一个像抽象方法模式:工厂方法模式使用泛型-C#

//Abstract Product 
interface IPage 
{ 
    string pageType(); 
} 

//Concerete Product 1 
class ResumePage : IPage 
{ 
    public string pageType() 
    { 
     return "Resume Page"; 
    } 
} 

//Concrete Product 2 
class SummaryPage : IPage 
{ 
    public string pageType() 
    { 
    return "SummaryPage"; 
    } 
} 

//Fcatory Creator 
class FactoryCreator 
{ 
    public IPage CreateOnRequirement(int i) 
    { 
     if (i == 1) return new ResumePage(); 
     else { return new SummaryPage(); } 
    } 
} 


//Client/Consumer 

void Main() 
{ 

    FactoryCreator c = new FactoryCreator(); 
    IPage p; 
    p = c.CreateOnRequirement(1); 
    Console.WriteLine("Page Type is {0}", p.pageType()); 
    p = c.CreateOnRequirement(2); 
    Console.WriteLine("Page Type is {0}", p.pageType()); 
    Console.ReadLine(); 
} 

如何使用泛型的代码转换?

+2

什么是您的最终目标是什么?为什么你需要泛型? – 2010-03-23 12:54:35

+2

也许他想学习如何在工厂模式中使用泛型? – Niike2 2010-03-23 12:58:21

+0

@妮可,是的,你是对的。 – nanda 2010-03-23 13:03:40

回答

6

您可以使用通用签名实现该方法,然后创建传入类型参数的类型。

虽然您必须指定new()条件。
这意味着它只接受具有空构造函数的类型。

像这样:

public IPage CreateOnRequirement<TCreationType>() where TCreationType:IPage,new() 
{ 
    return new TCreationType();    
} 
+0

其中TCreationType:new(),IPage – Nagg 2010-03-23 12:59:54

+0

@Nagg:是的,谢谢。错过了。 – 2010-03-23 13:02:02

+0

感谢Simon花费你的时间。 – nanda 2010-03-23 13:05:49