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

C# 如何创建采用泛型基类型的方法,c#,generics,C#,Generics,我有类似于以下内容的内容,但我无法向printshelteradress方法提供House或Farm对象: public interface IAnimal { }; public interface IDomesticAnimal : IAnimal { }; public interface IHouseAnimal : IDomesticAnimal { }; public interface IFarmAnimal : IDomesticAnimal { }; public class

我有类似于以下内容的内容,但我无法向
printshelteradress
方法提供
House
Farm
对象:

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);
    }
}
这很管用,但我不喜欢使用
动态

我的最佳解决方案:

static void PrintShelterAddress(dynamic nonDescriptShelter)
{
    Console.WriteLine(nonDescriptShelter.Address);
}
将非通用基本接口添加到IAnimalShelter,并使用该接口:

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

static void PrintShelterAddress(IAnimalShelter nonDescriptShelter) { ... }
公共接口IAnimalShelter{String Address{get;set;};
公共接口IAnimalShelter:IAnimalShelter,其中T:IDomesticAnimal{};
静态无效打印ShelterAddress(IAnimalShelter nonDescriptShelter){…}
所以…


有没有比使用
dynamic
或向
IAnimalShelter
添加基本接口更好的解决方案?

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

public interface IAnimalShelter<out T> : .....
公共接口IAnimalShelter:。。。。。
public interface IAnimalShelter<out T> : .....