2013-10-06 93 views
0

繼承我有一個父類如何從通用母公司

public class GenericRepository<TEntity> where TEntity : class 
    { 
     //Implementation 
    } 

而且我想從這個類繼承,但我似乎無法得到它的權利,這裏是我的嘗試

public class CustomerRepository<Customer> : GenericRepository<Customer> 
    { 
     //implementation 
    } 

還是這個,

public class CustomerRepository<T> : GenericRepository<T> where T : new Customer() 
    { 

    } 

或者這一個

public class CustomerRepository<T> : GenericRepository<CustomerRepository<T>> where T : CustomerRepository<T> 
    { 

    } 

無論我做什麼,我都會收到此錯誤。請告訴我,我怎麼可以從該類繼承,類共享相同的命名空間

錯誤「GenericRepository」不包含一個構造函數參數0 CustomerRepository.cs

回答

0

看來你的基類有沒有參數沒有構造,如果是這樣的派生類必須聲明a.constructor和調用基類的構造函數的參數。

class MyBase { public MyBase(object art) { } } 
class Derived : MyBase { 
    public Derived() : base(null) { } 
} 

在這個例子中,如果你從Derived中刪除ctor,你會得到相同的錯誤。

+0

謝謝,我實現了一個無參數的父構造函數,並編譯它。謝謝 –

4

這聽起來像你想的非通用類從一個普通的一個繼承,像這樣:

public class CustomerRepository : GenericRepository<Customer> 
{ 
} 

如果你想這是一個通用類,縮小了泛型參數的類型(只允許Customer或派生型):

public class CustomerRepository<T> : GenericRepository<T> 
    where T : Customer 
{ 
} 

關於你的編譯時錯誤:

Error 'GenericRepository<Customer>' does not contain a constructor that takes 0 arguments

這意味着正是它說。您還沒有定義在派生類的構造函數,這意味着構造函數被隱式生成,就好像您已鍵入此:

public CustomerRepository() : base() { } 

然而,基類(GenericRepository<Customer>)沒有一個構造函數沒有參數。您需要在派生類CustomerRepository中顯式聲明構造函數,然後在基類上顯式調用構造函數。

1

您不需要重複類型參數的派生類,所以:

public class CustomerRepository : GenericRepository<Customer> 
    { 
     //implementation 
    } 

是你所需要的東西。

+0

謝謝,我只是嘗試過,仍然無法建立。同樣的確切錯誤。我將重新啓動Visual Studio以查看是否有幫助。 –

0

使用可以作爲寫:

public class CustomerRepository : GenericRepository<Customer> 
{ 
     //implementation 
}