【发布时间】:2019-02-06 00:19:27
【问题描述】:
好吧,我不知道为什么会这样。
我设置了一个属性,在我设置它之后,它在另一个类中为空。使用调试器单步执行它只会显示它已设置,并且它在其他类中为 null。
这是我的代码:(去掉所有不必要的代码)
public class SnakeGame : SenseHatSnake, ISnakeGame
{
private readonly IBody _body;
public SnakeGame(ISenseHat senseHat, IBody body)
: base(senseHat)
{
_body = body;
}
private void UpdateGame(Object state)
{
_movement.PreviousPositions.Add(new Position()
{
X = _movement.X,
Y = _movement.Y
});
if (_body.DetectCollision(_movement.X, _movement.Y))
{
GameOver();
}
}
}
它发生在 body 类中的 DetectCollision。
public class Body : IBody
{
private readonly IMovement _movement;
public Body(IMovement movement)
{
_movement = movement;
}
public bool DetectCollision(int x, int y)
{
for (int i = 1; i < Length + 1; i++)
{
if (_movement.PreviousPositions.Count > i)
{
int bX = _movement.PreviousPositions[_movement.PreviousPositions.Count - i - 1].X;
int bY = _movement.PreviousPositions[_movement.PreviousPositions.Count - i - 1].Y;
if (bX == x && bY == y)
{
return true;
}
}
}
return false;
}
}
我刚刚设置了_movement.PreviousPositions,我可以在调试器中看到它,但只要它在Body 中,_movement.PreviousPositions 就为空。
Movement.cs:
public class Movement : IMovement
{
public List<Position> PreviousPositions { get; set; }
}
注意:
我正在使用 DI,我在那里做错了吗? (Autofac)
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
var builder = new ContainerBuilder();
builder.RegisterType<Body>().As<IBody>();
builder.RegisterType<Display>().As<IDisplay>();
builder.RegisterType<Draw>().As<IDraw>();
builder.RegisterType<Food>().As<IFood>();
builder.RegisterType<Movement>().As<IMovement>();
builder.RegisterType<SnakeGame>().As<ISnakeGame>();
builder.RegisterType<ISenseHat>().As<ISenseHat>();
var container = builder.Build();
var body = container.Resolve<IBody>();
var display = container.Resolve<IDisplay>();
var draw = container.Resolve<IDraw>();
var food = container.Resolve<IFood>();
var movement = container.Resolve<IMovement>();
Task.Run(async () =>
{
ISenseHat senseHat = await SenseHatFactory.GetSenseHat().ConfigureAwait(false);
var snakeGame = new SnakeGame(senseHat, body, display, draw, food, movement);
snakeGame.Run();
});
}
}
【问题讨论】:
-
PreviousPositions在运动中。 (将该类添加到问题中) -
SnakeGame没有在您的问题中定义_movement,因此尚不清楚这与_body有何关系。 -
尝试在
PreviousPositions的设置器中设置断点。 -
@SelmanGenç 我做了,它已经设置好了。
-
如果您假设
Body将获得与SnakeGame相同的IMovement,那是不正确的。 Autofac 的默认注册是InstancePerDependency,所以Body和SnakeGame将各自获得自己独特的Movement实例。这是这里的问题吗?
标签: c# dependency-injection uwp autofac