创建变量类型“ T”的实例

时间:2019-07-31 09:00:45

标签: c# list generics instance

我有一个C#Point,其中有两个子类ColorPointAmountPoint

点级

public class Point
{
    double x; // Position x
    double y; // Position y

    public Point(double pos_x, double pos_y) // Constructor
    {
        this.x = pos_x;
        this.y = pos_y;
    }
}

public class ColorPoint : Point
{
    double color; // White value (0 to 255)
}

public class AmountPoint : Point
{
    int amount; // Amount of Persons standing at this point
}

现在在我的main类中,我想在列表中创建一个新的点

这应该看起来像这样:

public class main
{
    public main()
    {
        List<ColorPoint> colorList = new List<ColorPoint>(4);
        AddPoint<ColorPoint>(colorList);
    }

    public List<T> AddPoint<T>(List<T> pointList)
        where T : Point
    {
        pointList.Add(new T(0, 0)); // DOES NOT WORK (Cannot create instance of variable type 'T')
        pointList.Add(new Point(0, 0)); // DOES NOT WORK (Cannot convert Point to T)
    }
}

在两种情况下,变量coloramount都可以保留为null

1 个答案:

答案 0 :(得分:1)

您的代码无法编译。我无法想象为什么您会想做自己想做的事情。但是最接近合法实现的方法是:

class Program
{
    static void Main(string[] args)
    {
        List<ColorPoint> colorList = new List<ColorPoint>(4);
        AddPoint<ColorPoint>(colorList);
    }

    public static List<T> AddPoint<T>(List<T> pointList)
        where T : Point, new()
    {
        pointList.Add(new T());
        return pointList;
    }
}

public class Point
{
    double x; // Position x
    double y; // Position y

    public Point() : this(0, 0)
    {
    }

    public Point(double pos_x, double pos_y) // Constructor
    {
        this.x = pos_x;
        this.y = pos_y;
    }
}

public class ColorPoint : Point
{
    double color; // White value (0 to 255)

    public ColorPoint()
    {
    }

    public ColorPoint(double pos_x, double pos_y) : base(pos_x, pos_y)
    {
    }
}

public class AmountPoint : Point
{
    int amount; // Amount of Persons standing at this point

    public AmountPoint()
    {
    }

    public AmountPoint(double pos_x, double pos_y) : base(pos_x, pos_y)
    {
    }
}