2013-11-21 18 views
1

我有以下問題:C#:接口,而不是類變量定義

我有接口ILocation,其包括以獲取功能特徵的位置(在2D網格)。並不是所有的類都可以擁有這個接口,但是那些接口並不相關(不會相互繼承)。即具有此接口的類是Person,Item,BuildingBlock ...

現在我有class Location,它包含變量「block」。基本上任何東西都可以在那裏,有一個條件:它必須實現接口ILocation。我怎樣才能做到這一點?我不知道,哪個類將在這個變量中,因此必須將它指定爲Object,但我知道它必須實現ILocation。如何才能做到這一點?

在下面的示例中,我想要實現方法Symbol,它位於ILocation接口中。

public class Location :ILocation 
{ 
    public int X {get; set;} 
    public int Y {get; set;} 
    public Object block; 

    public Location (int x, int y, Object o) 
    { 
     X = x; 
     Y = y; 
     block = o; 
    } 

    public char Symbol() 
    { 
     return block.Symbol(); 
    } 
} 

而這當然會產生一個錯誤,因爲Object類的實例塊沒有實現ILocation。

那麼 - 如何告訴C#,變量中的「塊」可以是任何實現ILocation的對象?

感謝

茲比涅克

+2

用'ILocation'替換'Object'? –

回答

5

申報塊變量的位置:

public ILocation block; 

public Location (int x, int y, ILocation o) 
{ 
    X = x; 
    Y = y; 
    block = o; 
} 
+1

太棒了,它完美的作品! – Zbynek

0

無論說什麼lazyberezovsky或者,如果您還需要保持的確切類型塊的知識,你可以使用與泛型類似的東西:

public class Location<TBlock> : ILocation 
    where TBlock : ILocation 
{ 
    public int X { get; set; } 
    public int Y { get; set; } 
    public TBlock block; 

    public Location(int x, int y, TBlock o) 
    { 
     X = x; 
     Y = y; 
     block = o; 
    } 

    public char Symbol() 
    { 
     return block.Symbol(); 
    } 
} 
0

用ILocation替換對象。

public ILocation block; 
public Location (int x, int y, ILocation o) 

因此,只要您創建位置對象,就可以傳遞實現ILocation接口的任何對象。

var book = new Book();   // Book implements ILocation. 
var person = new Person();  // Person implements ILocation. 
var table = new Table();   // Table doesn't implement ILocation. 
var bookLocation = new Location(1, 2, book); 
var personLocation = new Location(2, 3, person); 
var tableLocation = new Location(2, 3, table); // Compile error as table doesn't implement ILocation,