。net核心中处理多态性的最佳做法

问题描述 投票:-1回答:1

假设我有3个A,B和C类:

public class A{

}

public class B : A{

}

public class C : A{

}

在我的Api中,我有:

 [HttpPost]
 public ActionResult Post([FromBody] A a)
 {   
   var new_a = addToDb(a); // add a to the db...
   return Created("", new_a);
 }

在此示例中,addToDb(A a)表示使用具有多态行为的存储库模式向数据库添加值。

问题在于,JSON转换器不会根据输入将A强制转换为B或C。什么是解决此问题的最佳选择?我已经尝试为每个派生类添加多个专用功能,例如:

 [HttpPost("/B")]
 public ActionResult Post([FromBody] B a)
 {
   var new_a = addToDb(a); // add a to the db...
   return Created("", new_a  as B);  
 }

但是添加所有这些功能感觉不正确。有更好的选择吗?请帮助

c# api asp.net-core polymorphism model-binding
1个回答
0
投票

您可以尝试

    [HttpPost]
    public ActionResult Post([FromBody] A a)
    {
        var new_a = addToDb(a); // add a to the db...
        if (a.GetType() == typeof(B))
            return Created("", (B)new_a);           
        else
            return Created("", (C)new_a);            
    }
© www.soinside.com 2019 - 2024. All rights reserved.