首页 > 解决方案 > 不同子类的相同方法

问题描述

我有一个带有两个子类的C#-Class和.PointColorPointAmountPoint

点级

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
}

现在我想要两件事。

  1. 我想要一个AdaptMeshPoints同时接受输入列表和输入列表的方法,ColorPoint并且AmountPoint我可以更改两者的公共参数(它们是 中的参数Point

  2. 我想告诉方法AdaptMeshPoints,它应该打印出子类的哪个参数。

这应该看起来像这样:

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

    public List<var> AdaptMeshPoints<var>(List<var> pointList, varType whatToPrint)
    {
        pointList[0].x = 45;
        Console.WriteLine(pointList[0].whatToPrint);
    }
}

标签: c#genericssubclass

解决方案


我假设这是您问题文本中的 C#,即使您的问题同时带有 C# 和 Java 标记。

为了能够设置pointList[0].x,您需要告诉编译器T将始终是 a Point(或从它继承的东西)。使用泛型类型约束 ( where T : Point) 执行此操作。

您还可以传递一个委托,该委托描述您要打印的属性:

public main()
{
    List<ColorPoint> colorList = new List<ColorPoint>(4);
    AdaptMeshPoints(colorList, x => x.color.ToString());
}

public List<T> AdaptMeshPoints<T>(List<T> pointList, Func<T, string> whatToPrint)
    where T : Point
{
    pointList[0].x = 45;
    Console.WriteLine(whatToPrint(pointList[0]));
}

推荐阅读