接口

2009-11-06 33 views
5

C#構造函數我知道,你不能在一個接口中的構造,但這裏是我想做的事:接口

interface ISomething 
{ 
     void FillWithDataRow(DataRow) 
} 


class FooClass<T> where T : ISomething , new() 
{ 
     void BarMethod(DataRow row) 
     { 
      T t = new T() 
      t.FillWithDataRow(row); 
     } 
    } 

我真的想用更換ISomethingFillWithDataRow方法莫名其妙的構造函數。

這樣,我的成員類可以實現接口,仍然是隻讀的(它不能用FillWithDataRow方法)。

有沒有人有模式,會做我想要的?

+0

你想要的成員類是隻讀的? – 2009-11-06 08:20:53

+0

重複 - 看看這裏http://stackoverflow.com/questions/619856/interface-defining-a-constructor-signature – Blounty 2009-11-06 08:25:01

+0

可能重複的[接口定義構造函數簽名?](https://stackoverflow.com/questions/619856 /接口限定-A-構造簽名) – Nisarg 2017-10-26 13:23:24

回答

3

(我應該先檢查,但我厭倦了 - 這多半是duplicate

要麼有工廠界面,要麼將Func<DataRow, T>傳入您的構造函數。 (他們大多是等價的,真正的接口可能是依賴注入更好,而代表小挑剔。)

例如:

interface ISomething 
{  
    // Normal stuff - I assume you still need the interface 
} 

class Something : ISomething 
{ 
    internal Something(DataRow row) 
    { 
     // ... 
    }   
} 

class FooClass<T> where T : ISomething , new() 
{ 
    private readonly Func<DataRow, T> factory; 

    internal FooClass(Func<DataRow, T> factory) 
    { 
     this.factory = factory; 
    } 

    void BarMethod(DataRow row) 
    { 
      T t = factory(row); 
    } 
} 

... 

FooClass<Something> x = new FooClass<Something>(row => new Something(row)); 
6

改爲使用抽象類?

你也可以擁有,如果你希望你的抽象類實現一個接口...

interface IFillable<T> { 
    void FillWith(T); 
} 

abstract class FooClass : IFillable<DataRow> { 
    public void FooClass(DataRow row){ 
     FillWith(row); 
    } 

    protected void FillWith(DataRow row); 
}