C# 创建变量类型的实例';T';
我有一个C# 创建变量类型的实例';T';,c#,list,generics,instance,C#,List,Generics,Instance,我有一个C#-ClassPoint,它有两个子类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; } }
C#
-ClassPoint
,它有两个子类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
}
现在在我的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)
}
}
公共类主
{
公用干管()
{
列表颜色列表=新列表(4);
添加点(颜色列表);
}
公共列表添加点(列表点列表)
其中T:点
{
pointList.Add(新的T(0,0));//不起作用(无法创建变量类型“T”的实例)
pointList.Add(新点(0,0));//不起作用(无法将点转换为T)
}
}
在这两种情况下,变量
color
或amount
都可以保留为null
。您的代码无法编译。我无法想象你为什么要做你想做的事。但最接近合法实施的方法是:
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)
{
}
}
类程序
{
静态void Main(字符串[]参数)
{
列表颜色列表=新列表(4);
添加点(颜色列表);
}
公共静态列表添加点(列表点列表)
其中T:Point,new()
{
添加(新的T());
返回点列表;
}
}
公共课点
{
双x;//位置x
双y;//位置y
公共点():此(0,0)
{
}
公共点(双位置x,双位置y)//构造函数
{
这个.x=位置x;
this.y=pos_y;
}
}
公共类颜色点:点
{
双色;//白色值(0到255)
公共色点()
{
}
公共色点(双位x,双位y):基准(位x,位y)
{
}
}
公共类数量点:点
{
int amount;//此时站立的人数
公共金额点()
{
}
公共金额点(双位x,双位y):基数(位x,位y)
{
}
}
您应该为点
类定义一个无参数构造函数(这没有任何意义),或者在每个派生类中定义一个构造函数,该构造函数将使用三个参数并调用base。如果您不这样做,那么您的代码将根本无法编译。您不能使用newt(0,0)
但是@Selvin我绝对不建议这样做。我的建议是重新设计上面的代码。如果你想在这个列表中添加一些东西,那么你应该事先知道它是什么类型的。OPs代码有点臭。