如何创建采用泛型基类型的方法

本文关键字:基类 泛型 类型 方法 何创建 创建 | 更新日期: 2023-09-27 18:22:44

我有类似于以下的东西,但我不能向PrintShelterAddress方法提供HouseFarm对象:

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" });

编译,但按预期抛出运行时异常:无法将"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>中添加基本接口更好的解决方案?

如何创建采用泛型基类型的方法

嗯。。尝试使您的接口协变:

public interface IAnimalShelter<out T> : .....