Can abstract class be a parameter in a controller's action?

前端 未结 5 1717
既然无缘
既然无缘 2020-12-31 03:53

I have an Action function inside of a Controller, which is being called with AJAX. That Action is taking in 1 parameter. Client side, I construct a JSON object which shoul

5条回答
  •  长发绾君心
    2020-12-31 04:03

    You will have to create a child class of the abstract class and pass that instead. Abstract classes are fundamentally not permitted to be instantiated by themselves. However, if you have a C# method like:

    protected void Foo(MyAbstractClass param1)
    

    ...then you can still pass Foo an instance of a type that derives from MyAbstractClass. So you can create a concrete child class MyChildClass : MyAbstractClass and pass that to your method, and it should still work. You won't have to change the Foo method, but you will need some access to the C# code so you can create MyChildClass.

    If you're working with generics -- for example, if your method signature is:

    protected void Foo(IEnumerable param1)
    

    ...then it becomes more complicated, and you'll want to look into covariance and contravariance in C# generics.

提交回复
热议问题