2017-01-10 43 views
0

如果我有一個Bag類型的結構實現接口IGetProps,並且我有一個具有Bag類型成員變量的類商店,我可以在Store的實現中指定我希望Store類通過它的成員提供IGetProps型袋。C#:我可以指定一個類的成員結構是一個繼承接口的實現者嗎?

包不能更改爲一個類,以便我可以繼承它。 IGetProps有很多方法,所以我不想用Store中的方法顯式包裝每個方法。

如:

interface IGetProps 
{ 
    int GetA(); 
    int GetB(); 
} 

struct Bag : IGetProps 
{ 
    public int GetA() { return 0;} 
    public int GetB() { return 1;} 
    ... // Many more methods 
} 

class Store : IGetProps 
{ 
    private Bag bag;  // <--- Can I designate bag to be the provide of IGetProps for Store? 
} 
+0

不,你不能。 但是,您可以從包中繼承商店。 – dgorti

+0

@dgorti類不能從結構繼承。 http://stackoverflow.com/questions/15408667/inherit-from-struct – Nico

+0

爲什麼'Bag'是一個結構?既然你指出它有更多的方法_,這似乎表明應該使用'class',因爲結構通常意味着用值類型語義來建模不可變對象。 –

回答

0

簡單的答案是 「否」 你的類不能從structMSDN繼承。

對於類沒有繼承結構。結構 不能從另一個結構或類繼承,並且它不能是類的基 。但是,結構繼承自基類Object。一個 結構可以實現接口,它的確如類 所做的那樣。

然而,像這樣的東西可以工作,它仍然包裝的方法,但儘可能容易地完成。除此之外,沒有其他辦法。

interface IGetProps 
{ 
    int GetA(); 
    int GetB(); 
} 

struct Bag : IGetProps 
{ 
    public int GetA() { return 0; } 
    public int GetB() { return 1; } 
} 

class Store : IGetProps 
{ 
    private Bag bag;  // <--- Can I designate bag to be the provide of IGetProps for Store? 

    public int GetA() => bag.GetA(); // <--- c# 6.0 syntax for wrapping a method 

    public int GetB() => bag.GetB(); 
} 

我們實現接口的方法,但是接口中的方法將執行結構GetA()GetB()方法。當然,我們需要將bag分配給某些東西(即,一個contrucutor變量或屬性)。

class Store : IGetProps 
{ 
    public Store(Bag bag) 
    { 
     this.bag = bag; 
    } 

    private Bag bag;  // <--- Can I designate bag to be the provide of IGetProps for Store? 

    public int GetA() => bag.GetA(); 

    public int GetB() => bag.GetB(); 
} 
相關問題