是否可以声明全局常量?也就是说,所有类中都有常量?当我尝试在类之外声明一个常量时,就像我对枚举一样,我得到一个解析错误.
我一直用这种方式使用枚举,但枚举仅限于整数,我想使用易于使用的单词而不是浮点值.
例; 我想在任何课程中都可以使用以下内容:
const float fast = 1.5f;
const float normal = 1f;
const float slow = .75f;
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过为速度名称创建一个枚举(速度)来解决这个问题,然后创建一个静态方法SpeedNum()来读取枚举Speed和return一个相关的值,但每次都需要这么多额外的写法,我希望有更优雅的东西:
例如:
public double function SpeedNum(Speed speed)
{
switch (speed)
{
case speed.fast: return 1.5;
case speed.normal: return 1f;
case speed.slow: return .75f;
}
}
Run Code Online (Sandbox Code Playgroud) 我找不到与我匹配的特定问题,我认为这与我使用一个参数,一个字符串创建EventArgs的子类这一事实有关.当我尝试编译时,它似乎告诉我ScanInfoEventArgs没有一个构造函数,当它显然(至少对我来说).
我只包含了我认为适用的代码.看起来这么简单,我不知所措.
public partial class MainWindow : Window
{
Coffee coffeeOnHand;
SweetTea sweetTeaOnHand;
BlueberryMuffin blueberryMuffinOnHand;
public MainWindow()
{
InitializeComponent();
//The following reads the inventory from file, and assigns each inventory item to the Coffee, SweatTea
//and BlueberryMuffin objects in memory.
using (Stream input = File.OpenRead("inventory.dat"))
{
BinaryFormatter formatter = new BinaryFormatter();
coffeeOnHand = (Coffee)formatter.Deserialize(input);
sweetTeaOnHand = (SweetTea)formatter.Deserialize(input);
blueberryMuffinOnHand = (BlueberryMuffin)formatter.Deserialize(input);
}
//The following adds whatever information is loaded from the objects on file from above
//into the dropdown box in …Run Code Online (Sandbox Code Playgroud) 我有一个抽象类Animal,其中的类继承了该类的变量.例如,Name字符串将包含该类所代表的动物的名称.
我的问题是,我可以要求在子构造函数中初始化这些变量吗?我想确保Cat.cs,Dog.cs等实际存储一个名称.我相信我可以创建一个虚拟的Start()或Awake()方法,但这只能确保Name字符串中包含某些内容,而不是动物的实际名称.
我收到以下代码的上述错误:
public class Sheep : Animal {
//hpMax = 100;
//power = 10;
//defense = 10;
//speed = 10;
animalName = "Sheep Test";
public override void Attack()
{
Debug.Log(animalName);
}
}
Run Code Online (Sandbox Code Playgroud)
似乎我无法在方法之外分配变量.是这样的吗?这意味着我必须创建一个"AssignStats()"方法来分配HPMax,电源,防御,速度等.我认为可能很清楚为什么我要避免每次调用时都将这个添加的步骤添加到代码中动物对象.
还是我错过了一些明显的东西?
我有一个调用第一个对话框的功能,然后需要等待用户按空格键才能显示第二个对话框.我可以使用协程轻松完成此任务,通过在while循环中产生如下:
message.PlayMessage();
while (Input.GetKeyDown (KeyCode.Space) == false) {
yield return null;
}
message.PlayMessage(2);
Run Code Online (Sandbox Code Playgroud)
我的问题是:这是一个奇怪的解决方案吗?我觉得可能有一个实际的功能,我担心这可能是无缘无故地占用了大量的系统资源.