我是编程新手,正在尝试学习 C# 以进行 Windows 8 应用程序开发。我正在使用“Head First C# - 3rd Edition”一书。第一个例子似乎失败了。对于那些有这本书的人,这在第33页列出。在下面的代码中,我已经去掉了不必要的方法,只留下了相关的代码。
public sealed partial class MainPage : Save_the_Humans.Common.LayoutAwarePage
{
public MainPage()
{
Random random = new Random();
this.InitializeComponent();
}
private void startButton_Click(object sender, RoutedEventArgs e)
{
AddEnemy();
}
private void AddEnemy()
{
ContentControl enemy = new ContentControl();
enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
playArea.Children.Add(enemy);
}
private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
{
Storyboard storyBoard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
DoubleAnimation animation = new DoubleAnimation()
{
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
};
Storyboard.SetTarget(animation, enemy);
Storyboard.SetTargetProperty(animation, propertyToAnimate);
storyBoard.Children.Add(animation);
storyBoard.Begin();
}
}
问题在于实例化字段“随机”的使用。编译时错误显示“名称‘随机’在当前上下文中不存在。” 我不够熟练,无法知道可能导致问题的原因。
AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");