大家好,我是 C# 的新手,我遇到了一些问题。我目前正在为学校做作业,我真的被困在这部分了。我盯着它看了好几个小时,用谷歌搜索了好几个小时,我很幸运。我在下面列出了到目前为止的内容。
方向不是很好。
“为 4 个图像状态创建一个公共(public)枚举 CharacterState:Attacking、Defending、Idle 和 Dead。 现在创建一个成员变量 state 来保存角色状态和一个带有 get 的公共(public)属性 State 并设置。现在,填写 get 和 set 的默认行为以返回/设置 state 的值。”
任何帮助将不胜感激!谢谢
namespace WPFBattle
{
class CharacterImage: System.Windows.Controls.Image
{
public enum Attacking{
}
public enum Defending{
}
public enum Idle{
}
public enum Dead{
}
public ImageSource IdleImageSource { get; set; }
public ImageSource AttackingImageSource { get; set; }
public ImageSource TakeDamageImageSource { get; set; }
public ImageSource DeadImageSource { get; set; }
protected void UpdateImageSource()
{
switch (State)
{
case CharacterState.Attacking:
this.Source = AttackingImageSource;
break;
case CharacterState.TakeDamage:
this.Source = TakeDamageImageSource;
break;
case CharacterState.Dead:
this.Source = DeadImageSource;
break;
case CharacterState.Idle:
default:
this.Source = IdleImageSource;
break;
}
}
protected override void OnRender(DrawingContext dc)
{
UpdateImageSource();
base.OnRender(dc);
}
public CharacterState State
{
get { return state; }
set
{
state = value;
this.Dispatcher.Invoke((Action)(() =>
{
UpdateImageSource();
}));
}
}
}
}
最佳答案
从您的枚举开始。
Create a public enum CharacterState for the 4 image states: Attacking, Defending, Idle, and Dead ...
根据您的代码,您为每个状态创建了一个枚举。枚举对于定义选项很有用,在您的情况下,您应该有一个定义角色状态的枚举。
public enum CharacterState {
Attacking,
Defending,
Idle,
Dead
}
... Now create a member variable state to hold the character state and a public property State with a get and set.
public class Character {
public Character()
{
State = CharacterState.Idle;
}
private CharacterState state; //-Member variable (private)
public CharacterState State
{ get
{
return state; // note the casing in State and state
}
set
{
State = value;
}
}
然后您可以通过其 State 属性访问角色的当前状态。
var character = new Character();
CharacterState state = character.State; // returns Idle.
// or set it
character.State = CharacterState.Attacking;
Console.WriteLine($"Take cover! character is {character.State}");
//- logs "Take cover! character is Attacking"
希望这能澄清事情。
关于C# 关于枚举方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40797179/