[英]c# Use of unassigned local variable OR object instance not set to a reference?
The following is a piece of code that does not seem to be working in c# even though it seems acceptable in c++. 以下是一段代码,即使它在c ++中似乎可以接受,但似乎在c#中不起作用。 C# seems to have different standards for object instantiation. C#似乎对对象实例化有不同的标准。
IList<PointF> vertices = null;
float radius = (int)(bitmap.Width/3);
for (double theta = 0; theta < 2 * 3.14; theta += 0.1)
{
PointF temp = new PointF();
temp.X = centre.X + radius*((float)(Math.Cos(theta)));
temp.Y = centre.Y + radius*((float)(Math.Sin(theta)));
vertices.Add(temp);
}
Where IList is an interface, and PointF is a struct. 其中IList是接口,而PointF是结构。 Tbh I do not know the differences when implementing interfaces vs classes. 我不知道实现接口和类时的区别。
If I do not assign "null" to vertices the code does not compile. 如果我不将“ null”分配给顶点,则代码不会编译。 However, if I do assign null then at runtime I get an error "object instance not set to a reference of an object" (because vertices is declared as null). 但是,如果我确实分配了null,则在运行时会出现错误“对象实例未设置为对象的引用”(因为顶点被声明为null)。 How can I get around this error? 如何解决这个错误?
您必须实例化列表实例:
IList<PointF> vertices = new List<PointF>();
尝试为实现IList<PointF>
顶点创建一个实例,例如:
IList<PointF> vertices = new List<PointF>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.