[英]Using abstract class as a generic type
Is there any way to use an abstract class as a generic type?有没有办法使用抽象 class 作为泛型类型? 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.
我收到一个错误,无法对变量 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:最终,在我的 .NET Core Startup 中,我希望能够拥有以下内容:
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:由于使用的是
IAnimalBehavior<AnimalBase>
,而不是IAnimalBehavior<Cat>
,因此此结构有效:
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:如果您在 T 上进行区分,则拥有
IAnimalBehavior<T>
是有意义的:
public class CatBehavior : IAnimalBehavior<Cat> { }
public class DogBehavior : IAnimalBehavior<Dog> { }
...
services.AddScoped<IAnimalBehavior<Cat>, CatBehavior>();
services.AddScoped<IAnimalBehavior<Dog>, CatBehavior>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.