我正在按照本书的步骤进行操作:“大脑友好指南:Head First C#'作者:O' Reilly Media
并且遇到了此错误'Windows.UI.Xaml.Duration' is a 'type' but is used like a 'variable'
插入此代码Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)));
我想知道为什么我会收到此错误,我该怎么做才能修复它?
下面是书中描述的完整代码方法,如果它有帮助,如果它只是造成混乱并且使用户难以阅读文本我将删除该方法。
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();
}
答案 0 :(得分:4)
编译器试图告诉您,您不能使用类型Duration
的名称来命名匿名类型的字段,因为您的初始化程序语法不正确:您在new DoubleAnimation()
之后添加了分号,因此初始化程序的其余部分被视为独立的代码块。
这是正确的语法:
DoubleAnimation animation = new DoubleAnimation {
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
};
我在new DoubleAnimation
之后删除了括号,因为调用了默认构造函数。我还用逗号替换了分号以符合C#语法。
答案 1 :(得分:1)
正如Jesse所指出的那样,你应该删除分号并用逗号替换它们:
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();
}