The following results in a NullReferenceException. It tells me that the "drawObjs.Add(drawObj);" - Object reference not set to an instance of an object. I don't understand why this is not set to an instance?
Th开发者_运维知识库e list:
List<drawObject> drawObjs;
The method which add's to the list:
public void createDrawObj()
{
drawObject drawObj = new drawObject(100,100,100,100,10);
drawObjs.Add(drawObj);
}
And the class itself:
class drawObject
{
float _posX;
float _posY;
float _sizeX;
float _sizeY;
float _cr;
public drawObject(float posX, float posY, float sizeX, float sizeY, float cr)
{
_posX = posX;
_posY = posY;
_sizeX = sizeX;
_sizeY = sizeY;
}
public GraphicsPath objPath()
{
GraphicsPath Path = new GraphicsPath();
Path.AddLine(_posX + _cr, _posY, _posX + _sizeX - (_cr * 2), _posY);
Path.AddArc(_posX + _sizeX - (_cr * 2), _posY, _cr * 2, _cr * 2, 270, 90);
Path.AddLine(_posX + _sizeX, _posY + _cr, _posX + _sizeX, _posY + _sizeY - (_cr * 2));
Path.AddArc(_posX + _sizeX - (_cr * 2), _posY + _sizeY - (_cr * 2), _cr * 2, _cr * 2, 0, 90);
Path.AddLine(_posX + _sizeX - (_cr * 2), _posY + _sizeY, _posX + _cr, _posY + _sizeY);
Path.AddArc(_posX, _posY + _sizeY - (_cr * 2), _cr * 2, _cr * 2, 90, 90);
Path.AddLine(_posX, _posY + _sizeY - (_cr * 2), _posX, _posY + _cr);
Path.AddArc(_posX, _posY, _cr * 2, _cr * 2, 180, 90);
Path.CloseFigure();
return Path;
}
public LinearGradientBrush objBrush(int objColor)
{
LinearGradientBrush lgb;
if (objColor == 1)
{
lgb = new LinearGradientBrush(new PointF(_posX + (_sizeX / 2), _posY), new PointF(_posX + (_sizeX / 2), _posY + _sizeY), Color.RosyBrown, Color.Red);
}
else
{
lgb = new LinearGradientBrush(new PointF(_posX + (_sizeX / 2), _posY), new PointF(_posX + (_sizeX / 2), _posY + _sizeY), Color.GreenYellow, Color.Green);
}
return lgb;
}
}
You need to instantiate drawObjs
- without it, it is a null reference:
List<drawObject> drawObjs = new List<drawObject>();
Instansiate your list:
List<drawObject> drawObjs = List<drawObject>();
If you used type inference you might be less likely to make this mistake.
var drawObjs = new List<drawObject>();
精彩评论