C# 持续时间是一种类型,但用作变量
本文关键字:类型 变量 一种 持续时间 | 更新日期: 2023-09-27 18:34:37
我正在遵循O'Reilly Media的"大脑友好指南:Head First C#"一书的步骤
并且遇到了此错误'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();
}
编译器试图告诉您,您不能使用类型Duration
的名称来命名匿名类型的字段,因为您的初始值设定项语法不正确:您在 new DoubleAnimation()
后放置了一个分号,因此初始值设定项的其余部分被视为独立的代码块。
这是正确的语法:
DoubleAnimation animation = new DoubleAnimation {
From = from,
To = to,
Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6)))
};
我删除了new DoubleAnimation
后的括号,因为调用了默认构造函数。我还用逗号替换了分号以符合 C# 语法。
正如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();
}