c# - 不同子类的相同方法
问题描述
我有一个带有两个子类的C#
-Class和.Point
ColorPoint
AmountPoint
点级
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
}
现在我想要两件事。
我想要一个
AdaptMeshPoints
同时接受输入列表和输入列表的方法,ColorPoint
并且AmountPoint
我可以更改两者的公共参数(它们是 中的参数Point
)我想告诉方法
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#,即使您的问题同时带有 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]));
}
推荐阅读
- node.js - Sequelize:在列查询中使用函数
- pytest - pytest:如何从文件中读取设备列表?
- makefile - 未找到模式时 patsubst 的返回值
- java - 将 DELETE 查询与 COUCHBASE DATABASE 一起使用
- java - Apache Velocity:替换换行符不起作用
- java - 如何将库中的值作为默认值连接并在应用程序明确定义属性后覆盖它
- c# - 使用 Selenium 完成 Internet Explorer 身份验证对话框
- javascript - window.open 在 echo 中不起作用
- c# - 如何在 C# 中的 FindByText 之后取消选中任何复选框 ListItem?
- angular - Dockerized Angular/nginx 应用程序不与 rest api 对话