我創建了一個具有 2 個型別引數的泛型類,但我無法為具有相同型別的 List principalList賦值。_D_Data.GetGrupoProductoList() 回傳一個List<E_grupo_producto>
public class N_TablaSolaBase<TPrincipalInfo, TData>
where TPrincipalInfo : E_grupo_producto, new()
where TData : D_Producto, new()
{
private TPrincipalInfo principalInfo= new TPrincipalInfo();
private List<TPrincipalInfo> principalList = new List<TPrincipalInfo>();
private TData _D_Data = new();
public List<TPrincipalInfo> GetPrincipalList()
{
var lista = _D_Data.GetGrupoProductoList();
MessageBox.Show((lista.GetType() == principalList.GetType()).ToString());
// show true
principalList = lista
// Can't convert List<E_grupo_producto> to List<TPrincipalInfo>
return principalList;
}
uj5u.com熱心網友回復:
你有一個方差問題。
如果你有; class Animal, class Dog : Animal& class Cat : Animal. 然后List<Animal>可以存盤和檢索任何動物。但是如果呼叫者期待 a List<Dog>,那么你不能給他們 a List<Animal>,因為其中可能有 a Cat。但是,如果呼叫者要求 a List<Animal>,你不能給他們 a List<Dog>,因為呼叫者可能會嘗試在Cat其中放入 a 。
您允許呼叫者class N_TablaSolaBase<TPrincipalInfo>指定他們是想要 aList<E_grupo_producto>還是只想要 a List<OtherProduct>。class OtherProduct : E_grupo_producto如果他們只要求List<OtherProduct>,你不能給他們一個List<E_grupo_producto>。
如果型別實際匹配,您可以添加運行時強制轉換以回傳串列。但是,如果唯一支持的值是 ,為什么還要使用泛型引數E_grupo_producto呢?
var lista = _D_Data.GetGrupoProductoList() as List<TPrincipalInfo>
?? throw new NotSupportedException();
或者您可以更改您的D_Producto類以添加一個通用引數,以確保GetGrupoProductoList回傳一個List<TPrincipalInfo>.
public class N_TablaSolaBase<TPrincipalInfo, TData>
where TPrincipalInfo : E_grupo_producto, new()
where TData : D_Producto<TPrincipalInfo>, new() {...}
public class D_Producto<TPrincipalInfo>
where TPrincipalInfo : E_grupo_producto, new() {
public List<TPrincipalInfo> GetGrupoProductoList() {...}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/511206.html
標籤:C#仿制药where子句
下一篇:與任意數量的泛型型別相交
