Search Unity

Question Cannot declare generic list as member of parent class

Discussion in 'Scripting' started by unity_o1B6N3bj49SbRA, Feb 11, 2024.

  1. unity_o1B6N3bj49SbRA

    unity_o1B6N3bj49SbRA

    Joined:
    Sep 19, 2020
    Posts:
    2
    Created a script like the following to define a class called ScrollViewController, and I want to inherit it in multiple classes. At this time, I prepared a virtual property named DataList with a generic type list as its element, and I want to allow specifying the data type in the child classes.

    # ScrollViewController.cs
    Code (CSharp):
    1. abstract class ScrollViewController<T> : MonoBehaviour
    2. {
    3.     protected virtual List<T> DataList
    4.     {
    5.         get { return dataList; }
    6.         set { dataList = value; }
    7.     }
    8.     private List<T> dataList;
    9. }
    # EngineerScrollViewController.cs
    Code (CSharp):
    1. class EngineerScrollViewController : ScrollViewController<Engineer>
    2. {
    3.     private List<Engineer> dataList = new List<Engineer>();
    4.     protected override List<Engineer> DataList
    5.     {
    6.         get { return dataList; }
    7.         set { dataList = value; }
    8.     }
    9. }
    However, I encountered an error message like below. Do you have any solutions to resolve this?

    Assets/Scripts/ScrollViewController.cs(51,24): error CS0029: Cannot implicitly convert type 'System.Collections.Generic.List<Engineer>' to 'System.Collections.Generic.List<T>'


    The article I referred to:
    https://stackoverflow.com/questions/63383863/declare-generic-list-as-member-of-parent-class
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,840
    The property here seems completely unnecessary.

    Just have a protected member:
    Code (CSharp):
    1. public abstract class ScrollViewController<T> : MonoBehaviour
    2. {
    3.     protected List<T> dataList = new List<T>();
    4. }
     
  3. unity_o1B6N3bj49SbRA

    unity_o1B6N3bj49SbRA

    Joined:
    Sep 19, 2020
    Posts:
    2
    Solved, thank a lot!