c# - 有没有办法在 c# 中将 2 种不同类型添加到新列表中?
问题描述
我正在尝试将 2 个列表添加在一起,但它们都是不同的类型,有没有办法做到这一点?
我的 2 个清单
var customer = _context.GetInsuredData.FromSqlRaw("Execute dbo.GetDataID {0}", id).ToList();
var vehicle = _context.GetVehicleData.FromSqlRaw("Execute dbo.GetDataVehicle {0}", id).ToList();
我的背景:
public virtual DbQuery<Insured> GetInsuredData { get; set; }
public virtual DbQuery<Vehicle> GetVehicleData { get; set; }
解决方案
对的,这是可能的。
选项 1 - 让类实现一个公共接口(或继承一个公共基类):
public interface ICommonInterface
{ }
public class Insured : ICommonInterface
{ }
public class Vehicle : ICommonInterface
{ }
...然后使用具有接口泛型类型的列表:
var list = new List<ICommonInterface>();
objectList.AddRange(insureds);
objectList.AddRange(vehicles);
选项 2 - 使用泛型类型声明一个列表object
:
var list = new List<object>();
list.AddRange(insureds);
list.AddRange(vehicles);
您可能需要重新考虑为什么要这样做。这些课程有共同点吗?然后使用接口/基类选项。如果不是,将不同类型的对象添加到同一个列表的原因是什么?您实际尝试解决的问题可能与此问题无关。
推荐阅读
- javascript - 甚至在用户在警报窗口上按下“确定”之前,Javascript 代码就会被执行
- linux - /usr/bin/ld 编译 Fortran 77 代码时出错
- r - 在 R 的 plot() 中,box() 与 R 中的轴线重叠
- javascript - 动态替换数组中的 JSON 对象
- javascript - 从请求标头或响应标头获取 jwt 令牌
- sqlite - SQLite 将多个值设置为特定的外键
- reactjs - 当我使用 useContext 挂钩时,为什么包裹在 forwardRef 中的功能组件会收到空引用?
- python - 如何在python中使用按位运算符?
- excel - 如何在 uipath 中使用动态调用 vba 更改 excel 中的行高
- python - 如何正确允许使用 Flask CORS 进行跨域请求?