Is there any way to use an abstract class as a generic type? I've given a very simple example below to simulate what I need. I get an error that an implicit conversion cannot be made for variable genericBehavior.
public abstract class AnimalBase { } // Cannot edit
public class Dog : AnimalBase { } // Cannot edit
public class Cat : AnimalBase { } // Cannot edit
public interface IAnimalBehavior<T> where T : AnimalBase { }
public class CatBehavior : IAnimalBehavior<Cat> { }
public class DogBehavior : IAnimalBehavior<Dog> { }
public class Startup
{
public Startup()
{
IAnimalBehavior<Cat> catBehavior = new CatBehavior();
IAnimalBehavior<AnimalBase> genericBehavior = new CatBehavior(); // This doesn't work
}
}
Ultimately, in my .NET Core Startup, I'd like to be able to have the following:
services.AddScoped<IAnimalBehavior<AnimalBase>, CatBehavior>();
or
services.AddScoped<IAnimalBehavior, CatBehavior>();
What's the best approach?
Since are using IAnimalBehavior<AnimalBase>
, and not IAnimalBehavior<Cat>
, then this structure works:
public interface IAnimalBehavior{ }
public class CatBehavior : IAnimalBehavior { }
public class DogBehavior : IAnimalBehavior { }
...
services.AddScoped<IAnimalBehavior, CatBehavior>();
Having IAnimalBehavior<T>
makes sense if you differentiate on T:
public class CatBehavior : IAnimalBehavior<Cat> { }
public class DogBehavior : IAnimalBehavior<Dog> { }
...
services.AddScoped<IAnimalBehavior<Cat>, CatBehavior>();
services.AddScoped<IAnimalBehavior<Dog>, CatBehavior>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.