【问题标题】:How to convert class into generic type如何将类转换为泛型
【发布时间】:2019-09-09 07:15:05
【问题描述】:

我有一个方法可以调用 api 服务来获取一些结果,并且方法的返回类型是类类型。对于单个类,我可以将名称指定为其返回类型并且工作正常。但在某些情况下,返回类型会发生变化。在那种情况下,我陷入了继续代码的困境。请指导我如何实现这一目标。

预期的解决方案: 我希望在 Details 类的 GetDoc(..) 方法中添加 if 条件。基于docType,我需要将GetRequest(Records)改为GetRequest(Employee)。

public Class Details{
public async Task<IActionResult> GetDoc(string docType){

var result= await _apiService.GetRequest<Records>(  //in some cases i need to change 'Records' to 'Employee'
url,//api url
...
)

}
}
----------
public class Record{
public Record(int id, string name){
ID=id;
Name=name
}
public int ID{get; set;}
public string Name{get;set;
}

public class Employee{
public Record(int id, string name){
ID=id;
Name=name
}
public int ID{get; set;}
public string Name{get;set;
}

public class ApiService{

public async Task<IactionResult> GetRequest<T>(string url, ....){
// here i am deserializing the response content using jsonconvert.
}

}


【问题讨论】:

  • 您可以根据docType 值使用if...else...
  • public async Task&lt;IActionResult&gt; GetDoc&lt;T&gt;(string docType)_apiService.GetRequest&lt;T&gt;(... 怎么样
  • 例如只有我给出了,Record 和 Employee.. 但它可以是 5 个不同的类。
  • @JeroenvanLangen 我正在从类型脚本中调用瘦详细信息类。有可能有 GetDoc 吗?我还没有这样尝试。我会试试这个。谢谢
  • @shobia 我相信switch 声明是通往这里的道路。

标签: c# templates generics asp.net-web-api types


【解决方案1】:

我建议不要像您正在接近的方式那样做,而是为每个端点创建不同的端点(我建议这样做是因为它看起来像是获取不同实体详细信息的端点)。所以,类似:

public class RecordController
{
    public async Task<IActionResult> GetDetails(int id)
    {
        var result = await _apiService.GetRequest<Record>(id);
        // Rest of the processing...
    }
}

然后是员工的另一个控制器:

public class EmployeeController
{
    public async Task<IActionResult> GetDetails(int id)
    {
        var result = await _apiService.GetRequest<Employee>(id);
        // Rest of the processing...
    }
}

如果其余逻辑允许,您可以进一步创建通用控制器,例如:

public abstract class MyBaseController<T>
{
    public virtual async Task<IActionResult> GetDetails(int id)
    {
        var result = await _apiService.GetRequest<T>(id);
        // Rest of the processing...
        // If the processing is not generic you may be able to use a delegate to handle that bit.
    }
}

现在在您的个人控制器中,您可以继承如下:

public class RecordController : MyBaseController<Record>
{
}

public class EmployeeController : MyBaseController<Employee>
{
}

实际上并没有对此进行测试。只是草拟了代码,为您提供设计类的想法。

【讨论】:

  • 感谢您的建议。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多