2012-02-07 77 views
2

我有類似於下面的東西的方法,但我不能提供HouseFarm對象的PrintShelterAddress方法:如何創建需要一個通用的基本類型

public interface IAnimal { }; 
public interface IDomesticAnimal : IAnimal { }; 
public interface IHouseAnimal : IDomesticAnimal { }; 
public interface IFarmAnimal : IDomesticAnimal { }; 

public class Animal : IAnimal { } 
public class DomesticAnimal : Animal, IDomesticAnimal { } 
public class Lion : Animal { } 
public class Cat : DomesticAnimal, IHouseAnimal { } 
public class Horse : DomesticAnimal, IFarmAnimal { } 

public interface IAnimalShelter<T> where T : IDomesticAnimal { String Address { get; set; } }; 
public interface IHouse : IAnimalShelter<IHouseAnimal> { }; 
public interface IFarm : IAnimalShelter<IFarmAnimal> { }; 

public class AnimalShelter<T> : IAnimalShelter<T> where T : IDomesticAnimal { public String Address { get; set; } } 
public class House : AnimalShelter<IHouseAnimal>, IHouse { } 
public class Farm : AnimalShelter<IFarmAnimal>, IFarm { } 

class Program 
{ 
    static void Main(string[] args) 
    { 
     PrintShelterAddress(new House() { Address = "MyHouse" }); // Error: argument type 'House' is not assignable to parameter type 'IAnimalShelter<IDomesticAnimal>' 

     // This makes sense as House is a IAnimalShelter<IHouseAnimal> 
     // and IHouseAnimal cannot be cast to its parent IDomesticAnimal 
     IAnimalShelter<IDomesticAnimal> nonDescriptShelter = new House(); // InvalidCastException: Unable to cast object of type 'House' to type 'IAnimalShelter`1[IDomesticAnimal]'. 
    } 

    static void PrintShelterAddress(IAnimalShelter<IDomesticAnimal> nonDescriptShelter) 
    { 
     Console.WriteLine(nonDescriptShelter.Address as string); 
    } 
} 

我試了一下:

手冊投:

PrintShelterAddress((IAnimalShelter<IDomesticAnimal>)new House() { Address = "MyHouse" }); 

編譯,但符合市場預期,引發運行TI我例外:無法投射'House'類型的對象來鍵入'IAnimalShelter`1 [IDomesticAnimal]'。

還有什麼我想:

static void PrintShelterAddress(dynamic nonDescriptShelter) 
{ 
    Console.WriteLine(nonDescriptShelter.Address); 
} 

這工作,但我並不熱衷於使用dynamic

我最好的解決辦法:

添加一個非通用基接口IAnimalShelter<T>和使用:

public interface IAnimalShelter { String Address { get; set; } }; 
public interface IAnimalShelter<T> : IAnimalShelter where T : IDomesticAnimal { }; 

static void PrintShelterAddress(IAnimalShelter nonDescriptShelter) { ... } 

所以...

難道還有比用更好的解決方案dynamic或添加基礎接口到IAnimalShelter<T>

回答

3

嗯..試着讓你的界面協變:

public interface IAnimalShelter<out T> : ..... 
相關問題