2012-07-25 110 views
0

我是新來的泛型,需要一些幫助。使用泛型實現接口

我想爲所有「變壓器」類創建一個接口來實現。要成爲「變壓器」,該課程必須至少包含一個變體T mapTo<T>(T t)

下面是我想用變壓器:
超載的一些方法...偉大的!看起來很簡單!

public class Transformer : ITransformer 
{ 
    public Transformer(IPerson instance) 
    { 
    } 

    public XmlDocument mapTo(XmlDocument xmlDocument) 
    { 
     // Transformation code would go here... 
     // For Example: 
     // element.InnerXml = instance.Name; 

     return xmlDocument; 
    } 

    public UIPerson maptTo(UIPerson person) 
    { 
     // Transformation code would go here... 
     // For Example: 
     // person.Name = instance.Name; 

     return person; 
    } 
} 

讓我們使用泛型定義接口:
馬麗娟的想法!

public interface ITransformer 
{ 
    T MapTo<T>(T t); 
} 

問題:
如果我在界面上使用泛型我的具體類實際上就是強制執行下列規定:

public T MapTo<T>(T t) 
{ 
    throw new NotImplementedException(); 
} 

這使得類看起來相當醜陋

public class Transformer : ITransformer 
{ 
    public Transformer(IPerson instance) 
    { 
    } 

    public XmlDocument MapTo(XmlDocument xmlDocument) 
    { 
     // Transformation code would go here... 
     // For Example: 
     // element.InnerXml = instance.Name; 

     return xmlDocument; 
    } 

    public UIPerson MapTo(UIPerson person) 
    { 
     // Transformation code would go here... 
     // For Example: 
     // person.Name = instance.Name; 

     return person; 
    } 

    public T MapTo<T>(T t) 
    { 
     throw new NotImplementedException(); 
    } 
} 

回答

2

也許添加通用參數接口定義:

public interface ITransformer<T> 
{ 
    T MapTo(T t); 
} 

而且實現你需要的所有映射:

public class Transformer : ITransformer<XmlDocument>, ITransformer<UIPerson> 
1

Tr Y本:

public interface ITransformer<T> 
{ 
    T MapTo(T t); 
} 

然後,當你實現你的接口,你的類是什麼樣子:

public class Transformer : ITransformer<XmlDocument> 
{ 
    public XmlDocument MapTo(XmlDocument t) 
    { 
     throw new NotImplementedException(); 
    } 
} 
+0

根據你想要的原始問題的代碼'public class Transformer:ITransformer ,IT變形器'。這不是問題,但值得指出,因爲在原始問題*中實現的接口不提供任何種類的多態性。 – 2012-07-25 12:20:56

+0

所以每個變壓器必須是唯一的?意思是,我不能簡單地超載? – 2012-07-25 12:25:40

1

你需要讓ITransformer接口通用。所以,你要這樣:

public interface ITransformer<T> 
{ 
    public T MapTo(T t); 
} 

然後,實現接口時,類可以通過界面,他們希望使用的類的類型參數:

public class Transformer : ITransformer<XmlDocument> 
{ 
    public XmlDocument MapTo(XmlDocument t) 
    { 
     //... 
    } 
} 

編輯:作爲lazyberezovsky下面說,沒有什麼能阻止你多次實現相同的接口:

public class Transformer : ITransformer<XmlDocument>, ITransformer<UIPerson> 

當然,這必須提供implementationati對於XmlDocument MapTo(XmlDocument t)UIPerson MapTo(UIPerson t)

+0

那麼每個變壓器必須是唯一的?意思是,我不能簡單地超載? – 2012-07-25 12:25:28

+0

是的,不幸的是。你可以重載具體類中的方法,沒有什麼能阻止你,但同樣不會有任何界面強制你,除非你爲每個類添加'ITransformer '。 – 2012-07-25 12:28:01

0

我認爲你正在試圖做的是有以下接口:

public interface ITransformer<TEntity> { 
    public TEntity MapTo(TEntity entity); 
} 
+0

那麼每個變壓器必須是唯一的?意思是,我不能簡單地超載? – 2012-07-25 12:24:54

+0

@PrisonerZERO,沒有你只是像上面的答案中顯示的那樣執行。 '公共課變壓器:IT變壓器,IT變壓器' – Mekswoll 2012-07-25 12:28:04